Side effects in macro arguments: evaluate this program's output and explain the increments. #include<stdio.h> #define MAN(x, y) ((x) > (y)) ? (x) : (y) int main() { int i = 10, j = 5, k = 0; k = MAN(++i, j++); printf("%d, %d, %d\n", i, j, k); return 0; }

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:

  • Macro: #define MAN(x, y) ((x) > (y)) ? (x) : (y).
  • Initial values: i = 10, j = 5.
  • Expression: 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:

Comparison: ++i → 11; j++ → compares as 5 then sets j = 6.Branch: true → evaluate ++ii = 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:

Outputs with “Garbage” imply uninitialized values; here all values are well-defined.Other numeric triplets contradict the documented increments.


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

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