typestar

Why macros need parentheses in C

Substitution ignores precedence, so every parameter and the whole body get brackets.

#define BAD_SQUARE(x) x * x
#define SQUARE(x) ((x) * (x))
#define MAX(a, b) ((a) > (b) ? (a) : (b))

int compare_expansions(void) {
    int wrong = BAD_SQUARE(1 + 2);
    int right = SQUARE(1 + 2);
    return right - wrong;
}

int double_evaluation(void) {
    int i = 1;
    int bigger = MAX(i++, 0);
    return bigger + i;
}

How it works

  1. Without brackets SQUARE(1 + 2) expands to 1 + 2 * 1 + 2.
  2. Wrapping the parameters and the result fixes it.
  3. A parameter used twice also evaluates its argument twice.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
302
Tokens
67
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 42 seconds.

Type this snippet

Step 2 of 4 in Macros, step 2 of 12 in Preprocessor & headers.

← Previous Next →