Course contentsShow
← C
Lesson 771 of 1,21911. The Preprocessor and BuildFree lesson

Avoiding magic numbers with macros

Avoiding magic numbers with macros

What you'll learn: How to use the #define preprocessor directive to replace mysterious numbers with meaningful names, making your code easier to read and maintain.

The mystery of the "Magic Number"

Imagine you are reading a recipe that says, "Bake the dough for 480." You’d immediately ask: 480 what? Seconds? Minutes? Degrees? In programming, we call a raw number dropped into the middle of code a "magic number." It’s "magic" because its purpose is unexplained, and if it appears in ten different places, changing it becomes a nightmare.

If you write if (age >= 21), it might be obvious today that 21 is the legal drinking age. But if you write price = items * 1.0825, someone reading your code later (including future you) will have no idea that 1.0825 represents the local sales tax rate for a specific city.

Meet the #define directive

The C preprocessor gives us a tool to solve this: the #define macro. Before your code is even compiled, the preprocessor does a "search and replace" throughout your file. You give a name to a value, and the preprocessor swaps the name for the value everywhere it appears.

By convention, we write these names in ALL_CAPS to signal to other programmers that this isn't a regular variable—it’s a constant defined by the preprocessor.

Macros in action

Look at how much clearer the code becomes when we label our numbers:

#include <stdio.h>

// Defining our constants at the top
#define SALES_TAX_RATE 0.0825
#define FREE_SHIPPING_THRESHOLD 50.00

int main() {
    double order_total = 65.25;

    // The code now reads like a sentence
    if (order_total > FREE_SHIPPING_THRESHOLD) {
        printf("You qualify for free shipping!\n");
    }

    double final_price = order_total + (order_total * SALES_TAX_RATE);
    printf("Final price: $%.2f", final_price);

    return 0;
}

Why this matters

Using macros provides two massive benefits:

  1. Readability: FREE_SHIPPING_THRESHOLD tells a story; 50.00 is just a digit.
  2. Maintainability: If the tax rate changes to 0.085, you only have to change it in one place (the #define line) instead of hunting through thousands of lines of code to find every instance of that specific number.

Key takeaway

Use #define to give descriptive names to constant values, turning "magic numbers" into self-documenting code.