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

Side effects in macro arguments

Side effects in macro arguments

What you'll learn: Why using increment operators or function calls inside a macro can lead to unexpected and buggy behavior.

The Copy-Paste Trap

Macros are not functions; they are simple "find and replace" tools. When you pass an argument to a macro, the preprocessor takes the exact text you wrote and pastes it everywhere that argument appears in the macro definition.

This creates a hidden danger called side effects. If your argument does something extra—like incrementing a variable with ++—that action might happen multiple times without you realizing it.

Double Trouble

Imagine you have a macro to find the square of a number. You might write it like this:

#include <stdio.h>

#define SQUARE(x) ((x) * (x))

int main() {
    int a = 5;
    
    // Danger: The argument has a side effect (a++)
    int result = SQUARE(a++); 
    
    printf("Result: %d\n", result);
    printf("Value of a: %d\n", a);
    
    return 0;
}

You might expect a to be 5, get squared to 25, and then increment once to 6. However, the preprocessor expands SQUARE(a++) into ((a++) * (a++)).

Look closely at that expanded code. The variable a is now incremented twice. Depending on how the compiler handles the math, a could end up as 7, and the result might be 30 (5×65 \times 6) instead of 25. The "side effect" of the increment operator was pasted into the code twice because the variable name x appeared twice in the macro definition.

Analogy: The Cooking Recipe

Think of a macro like a recipe. If the recipe says, "Take the Ingredient and chop it, then take the Ingredient and boil it," and you decide that your Ingredient is "an apple that I must wash first," the recipe becomes:

  1. Wash an apple and chop it.
  2. Wash an apple and boil it.

You ended up washing two apples (or the same apple twice) because the instructions told you to use the ingredient twice. A real C function, by contrast, would "wash" the apple once and then use that same clean apple for every step.

How to Stay Safe

To avoid these bugs, never pass expressions that change values (like i++, --j, or func()) into a macro. Always perform the calculation or increment on a separate line before calling the macro.

Key takeaway

Macros literally duplicate their arguments in the code, which can cause side effects like ++ to trigger multiple times and corrupt your data.