</>EmbeddedInterview

Why should macro arguments and bodies be wrapped in parentheses?

EasyC Programming

Short answer: Macros substitute text, so operator precedence around and inside the macro can change the meaning. Put parentheses around every use of each argument and around the whole body so the macro behaves like a single value.

#define DOUBLE(x) x + x
int r = 3 * DOUBLE(2);        /* expands to 3 * 2 + 2 = 8, not 12 */

#define SQUARE(x) (x * x)
int s = SQUARE(1 + 2);        /* expands to (1 + 2 * 1 + 2) = 5, not 9 */

Correct versions:

#define DOUBLE(x) ((x) + (x))
#define SQUARE(x) ((x) * (x))

Both kinds of parentheses are needed

  • Around arguments (x): protects against operators inside the argument (1 + 2).
  • Around the body ( ... ): protects against operators next to the macro where it is used (3 * DOUBLE(2)).

Other macro hygiene rules

  • Multi-statement macros: wrap in do { ... } while (0) (next question).
  • Arguments with side effects are still evaluated multiple times; parentheses do not fix that. Document it or use an inline function.
  • Avoid names that clash: local variables inside macros should have unusual names (t_), because they can shadow the caller's variables.
  • Do not end a macro definition with a semicolon (#define X 5;), or if (a == X) ... becomes a syntax error.

Hardware register macros need the same care: #define REG_CTRL (*(volatile uint32_t *)(BASE + 0x04u)) has parentheses around the address arithmetic and the whole dereference, so REG_CTRL |= 1u; works as expected.