Difficulty: Medium
Correct Answer: 12, 6, 12
Explanation:
Introduction / Context:
This question highlights a common macro pitfall: arguments with side effects may be evaluated more than once due to how the ternary operator is expanded. Understanding when ++i
and j++
occur avoids undefined expectations and shows why function-like macros can be unsafe.
Given Data / Assumptions:
#define MAN(x, y) ((x) > (y)) ? (x) : (y)
.i = 10
, j = 5
.k = MAN(++i, j++)
.
Concept / Approach:
After expansion, the expression becomes ((++i) > (j++)) ? (++i) : (j++)
. The comparison evaluates both ++i
and j++
once: ++i
makes i = 11
; j++
compares with 5 and then increments j
to 6. Since 11 > 5, the true branch is selected, which evaluates ++i
again, making i = 12
and assigning k = 12
. The false-branch j++
is not evaluated again because the ternary chooses only one branch at runtime.
Step-by-Step Solution:
++i
→ 11; j++
→ compares as 5 then sets j = 6
.Branch: true → evaluate ++i
→ i = 12
and assign k = 12
.Final: i = 12
, j = 6
, k = 12
.
Verification / Alternative check:
Print intermediate values or rewrite as an inline function to avoid multiple evaluations. In a function, arguments would be evaluated once before the call.
Why Other Options Are Wrong:
Common Pitfalls:
Using macros with side-effectful arguments; forgetting that ++i
or j++
may execute more than once depending on the chosen branch.
Final Answer:
12, 6, 12.
Discussion & Comments