Course contentsShow
← C
Lesson 116 of 1,2192. Variables and TypesFree lesson

Macros vs. Const variables

Macros vs. Const variables

What you'll learn: How to decide between using the #define preprocessor and the const keyword when creating fixed values in your code.

In C, when you have a value that never changes—like the value of Pi or the maximum number of players in a game—you shouldn't just type the number over and over. You should give it a name. There are two primary ways to do this, and they work very differently behind the scenes.

The Macro: A "Find and Replace" Robot

Think of a macro (#define) as a simple text-editor robot. Before your code is even compiled, the robot scans your file. Every time it sees your macro name, it physically swaps it for the value you provided.

It’s like writing a letter and telling a computer to "Replace every instance of 'Home' with '123 Maple Street'." The computer doesn't know what an address is; it just swaps the text. Because this happens before the program runs, macros don't occupy memory like variables do, but they are "blind" to C’s type rules.

The Const: A "Locked" Box

A const variable is a real variable with a specific type (like int or float). However, you’ve put a permanent padlock on it. You are telling the compiler, "This is an integer, and if I ever try to change its value later, throw an error."

Because const variables have a type, the compiler can catch mistakes. If you try to put a word into a const int, the compiler will complain. This makes const much safer for complex programs.

Side-by-Side Comparison

Here is how they look in action:

#include <stdio.h>

// Macros are usually written in ALL_CAPS
#define PI 3.14159

int main() {
    // A const variable has a type (float)
    const float limit = 10.5;

    // Use them just like regular numbers
    float area = PI * 2 * 2;
    
    if (area > limit) {
        printf("Area is too large!");
    }

    // This would cause a compiler error:
    // limit = 20.0; 

    return 0;
}

Which should you use?

In modern C, the const variable is generally preferred. It respects the rules of the language, shows up better in debugging tools, and prevents "type" errors. Macros are still widely used for simple configuration flags or when you need to define a value that affects the size of an array before the program even starts.

Key takeaway:

Use #define for simple, global "find-and-replace" values, but use const when you want the safety of data types and compiler protection.