ProgrammingModerateProduct company OA
Why are multi-statement macros usually written as `#define M(x) do { ... } while (0)`?
- A. So the macro body runs exactly once even when the macro is used inside a loop
- B. So the macro gets its own stack frame like a function
- 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
- 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
- What is printed? c #define INC(x) x++; x++ int a = 0, b = 0; if (a > 5) INC(b); printf("%d", b);
- What is printed? c int x = 7 / 2 2.0; double y = 7 / 2.0 2; printf("%d %.1f", x, y);
- What is printed? c void move(int pp) { (pp)++; pp += 10; } int main(void) { int a[] = {1, 2, 3}; int p = a; move(&p); move(&p); printf("%d…
- Assume 32-bit unsigned int. What is printed? c unsigned x = 0xABCD; printf("%X %X", (x >> 4) & 0xF, (x & ~(0xFu << 8)) | (0x3u << 8));
- In C99, which declaration lets you allocate a rows × cols matrix of int (cols known at run time) with ONE malloc, use it as m[i][j], and…
- With 4-byte int, what is printed? c int a[4]; memset(a, 1, sizeof a); printf("%d", a[0]);