ProgrammingModerateProduct company OA

Why are multi-statement macros usually written as `#define M(x) do { ... } while (0)`?

  1. A. So the macro body runs exactly once even when the macro is used inside a loop
  2. B. So the macro gets its own stack frame like a function
  3. C. So the macro acts as one statement that needs a trailing semicolon, and works correctly as the body of an if-else without braces
  4. D. Because the preprocessor cannot expand braces unless they belong to a loop

Correct answer: C. So the macro acts as one statement that needs a trailing semicolon, and works correctly as the body of an if-else without braces

With plain braces, `if (c) M(x); else …` breaks: the ; after } ends the if and the else is orphaned. do { … } while (0) is a single statement that swallows the ;, and its local variables stay scoped. It has nothing to do with frames or with how many times code runs.

More C Programming questions

Exams that ask this topic