In C, the macro with three operands expands without extra parentheses. Determine the final value printed by this program.\n\n#include<stdio.h>\n#define MAX(a, b, c) (a>b? a>c? a : c: b>c? b : c)\n\nint main()\n{\n int x;\n x = MAX(3+2, 2+7, 3+7);\n printf("%d\n", x);\n return 0;\n}

Difficulty: Medium

Correct Answer: 10

Explanation:


Introduction / Context:
This problem checks your understanding of how function-like macros expand and how the conditional operator chooses among expressions. The macro MAX is written for three comparisons and is intentionally defined without extra parentheses around parameters. You must trace expansion and operator precedence to find the integer actually printed.



Given Data / Assumptions:

  • Macro: #define MAX(a, b, c) (a>b? a>c? a : c: b>c? b : c)
  • Call site: MAX(3+2, 2+7, 3+7)
  • Standard C operator precedence applies: + before > before ?: .
  • No arguments have side effects (only additions), so order of evaluation pitfalls are minimal here.


Concept / Approach:
When the preprocessor sees MAX(3+2, 2+7, 3+7), it performs pure textual substitution. The result is a nested conditional expression that compares the three arithmetic results. Because + binds tighter than >, and > binds tighter than ?:, the sums are computed, then the comparisons decide which value to select.



Step-by-Step Solution:
Expand: (3+2>2+7 ? 3+2>3+7 ? 3+2 : 3+7 : 2+7>3+7 ? 2+7 : 3+7)Compute additions: 3+2=5, 2+7=9, 3+7=10.Evaluate first comparison: 5>9 → false, go to else branch.Evaluate 9>10 → false; choose 3+7.3+7 = 10, so x becomes 10, which is printed.


Verification / Alternative check:
A quick mental maximum among 5, 9, and 10 is 10. Because there are no side effects, macro pitfalls do not alter the arithmetic results here, confirming the printed value.



Why Other Options Are Wrong:
5 and 9 are not the largest values; “3+7” is a textual expression, not a runtime result; “Undefined due to macro side effects” does not apply since the arguments have no side effects.



Common Pitfalls:
Assuming macros evaluate like functions with argument parentheses automatically; forgetting operator precedence; expecting undefined behavior where none exists; overlooking that nested ?: without parentheses is still well-defined by precedence rules.



Final Answer:
10

Discussion & Comments

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