Operator precedence and unsafe macros: predict the result.\n\n#include<stdio.h>\n#define SQUARE(x) xx\n\nint main()\n{\n float s = 10, u = 30, t = 2, a;\n a = 2(s - ut) / SQUARE(t); // expands to 2(s - ut) / t * t\n printf("Result = %f", a);\n return 0;\n}\n\nWhat will be printed?

Difficulty: Medium

Correct Answer: Result = -100.000000

Explanation:


Introduction / Context:
This illustrates how missing parentheses in macros can change computation order. In C, * and / associate left-to-right with the same precedence, which interacts with the textual expansion of macros.



Given Data / Assumptions:

  • SQUARE(t) expands to tt (without parentheses).
  • Expression is 2*(s - ut) / t * t after expansion.
  • s=10, u=30, t=2.


Concept / Approach:
Evaluate left to right: (A / t) * t, where A = 2(s - ut). Because of left associativity, the * t at the end cancels the division by t, leaving just A.



Step-by-Step Solution:
Compute s - ut = 10 - 302 = 10 - 60 = -50.Compute A = 2(s - ut) = 2(-50) = -100.After expansion: A / t * t = (-100) / 2 * 2 = (-50) * 2 = -100.printf prints "Result = -100.000000".



Verification / Alternative check:
Using a safer macro #define SQUARE(x) ((x)(x)) would yield a = 2(10 - 60) / (22) = (-100)/4 = -25.000000.



Why Other Options Are Wrong:
-25.000000: that is the intended math, but not what the unsafe macro computes.0 or 100: do not match the algebra with left-to-right evaluation.



Common Pitfalls:
Assuming SQUARE(x) is safe for any expression; forgetting that macro bodies should be wrapped as ((x)(x)).



Final Answer:
Result = -100.000000

More Questions from C Preprocessor

Discussion & Comments

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