</>EmbeddedInterview

Why are multi-line macros wrapped in do { } while(0)?

MediumC Programming

Short answer: It turns several statements into one statement that needs a trailing semicolon, so the macro behaves correctly everywhere a single statement can appear, especially in an if/else without braces. The compiler removes the "loop" completely, so it costs nothing.

#define SWAP(a, b) do { int t_ = (a); (a) = (b); (b) = t_; } while (0)

if (x > y)
    SWAP(x, y);      /* one statement: works */
else
    other();

What goes wrong without it

With only braces:

#define SWAP(a, b) { int t_ = (a); (a) = (b); (b) = t_; }

if (x > y)
    SWAP(x, y);      /* expands to { ... };  <- the ';' ends the if statement */
else                 /* error: 'else' without a previous 'if' */
    other();

With no braces at all, only the first statement would be controlled by the if, and the rest would always run.

Alternatives

  • A static inline function, which avoids the problem entirely and is type-checked; prefer it when possible.
  • GCC/Clang statement expressions ({ ... }) can also return a value, but they are a compiler extension, not standard C.
  • The comma operator (a(), b()) works for simple expression-only macros.

Typical embedded uses: logging macros that capture __FILE__ and __LINE__, ASSERT() macros that call a fault handler, and critical-section helpers:

#define CRITICAL(code) do { uint32_t pm_ = __get_PRIMASK(); __disable_irq(); \
                            code; __set_PRIMASK(pm_); } while (0)