Parenthesize a Simple Macro
Double a count without changing the order of arithmetic
The parts request doubles a sum. A function-like macro substitutes tokens before the expression is evaluated, so DOUBLE(2 + 3) needs parentheses around x and around the whole expansion. Without parentheses around the parameter, replacement can produce 2 + 3 * 2, which is 8 rather than 10 because multiplication happens first. Parentheses around the whole body also protect the result when it is part of a larger expression.
#include <stdio.h>
#define DOUBLE(x) ((x) * 2)
int main(void) {
int requested = DOUBLE(2 + 3);
printf("Requested: %d\n", requested);
return 0;
}
Run this to get Requested: 10. Expansion changes DOUBLE(2 + 3) into ((2 + 3) * 2) before the compiler evaluates the expression. Do not put a space between DOUBLE and ( in the definition, or you define a different kind of macro.
A regular function such as int double_count(int x) { return x * 2; } receives an already evaluated argument value and has a declared parameter type. A macro substitutes tokens and does not provide that parameter type check. Prefer a function for ordinary calculations. Neither form makes signed overflow safe; keep results in range.
A side effect is a change such as count++. A macro whose body contains its parameter twice can repeat that change. For example, substituting count++ into ((x) + (x)) produces two unsequenced modifications of the same variable: undefined behavior, not a predictable doubled result. Do not run that expression. Parentheses do not repair it. Use side-effect-free arguments for these macros.