Operator precedence and unsafe macros: predict the result.
#include
#define SQUARE(x) xx
int main()
{
float s = 10, u = 30, t = 2, a;
a = 2(s - ut) / SQUARE(t); // expands to 2(s - ut) / t * t
printf("Result = %f", a);
return 0;
}
What will be printed?
-
AResult = -100.000000
-
BResult = -25.000000
-
CResult = 0.000000
-
DResult = 100.000000
-
ENone of the above
Answer
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