Macro with do–while and external counter: how many times does it print? #include<stdio.h> #define FUN(arg) do { if (arg) printf("CuriousTab..."); } while (--i) int main() { int i = 2; FUN(i < 3); return 0; }

Difficulty: Medium

Correct Answer: CuriousTab... CuriousTab...

Explanation:


Introduction / Context:
This question highlights macro expansion, the common do–while(0) pattern (here slightly altered), and how a macro can legally reference and change a variable in the surrounding scope. It also examines short-circuit evaluations inside the loop body.


Given Data / Assumptions:

  • i is defined in main and visible to the macro expansion.
  • The macro expands to a do { ... } while(--i) loop.
  • The printf has no format specifiers; any extra argument would be ignored if present.


Concept / Approach:
Start with i = 2. The do executes once unconditionally, the if (i < 3) is true, so it prints once. Then the loop condition --i decrements i to 1, which is nonzero, so the loop repeats. On the second pass, the condition is still true, it prints again, and --i turns 1 to 0, terminating the loop. Total prints = 2.


Step-by-Step Solution:

Iteration 1: i = 2 → print → --i → i = 1.Iteration 2: i = 1 → print → --i → i = 0.Loop exits as condition becomes 0.


Verification / Alternative check:
Add printf(" i=%d\n", i); after the printf to trace the countdown 2 → 1 → 0.


Why Other Options Are Wrong:

Three prints require starting from i ≥ 3; not the case here.“No output” contradicts the clearly true condition on both passes.“Compilation error” is wrong; macros may contain control constructs.


Common Pitfalls:
Forgetting that the macro reuses the caller’s i; assuming the do–while always uses 0 in its condition.


Final Answer:
CuriousTab... CuriousTab....

More Questions from C Preprocessor

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion