Evaluate short-circuit and precedence for logical operators in C. What is printed? #include<stdio.h> int main() { int x, y, z; x = y = z = 1; z = ++x || ++y && ++z; printf("x=%d, y=%d, z=%d ", x, y, z); return 0; } Assume standard operator precedence (&& before ||) and short-circuit evaluation.
-
Ax=2, y=1, z=1
-
Bx=2, y=2, z=1
-
Cx=2, y=2, z=2
-
Dx=1, y=2, z=1
-
ENone of the above
Answer
Correct Answer: x=2, y=1, z=1
Explanation
Introduction / Context:This classic interview problem tests knowledge of operator precedence and short-circuiting with side effects from pre-increment operators.
Given Data / Assumptions:
- Initial values: x = y = z = 1.
- Expression: z = ++x || ++y && ++z.
- Precedence: ++ (unary) > && > ||.
- Short-circuit behavior: if the left of || is nonzero, the right side is not evaluated.
Concept / Approach:First evaluate ++x, then evaluate the || with the right-hand side (which itself contains &&) only if needed. Because ++x makes x nonzero (2), the left of || is true and the rest is skipped.
Step-by-Step Solution:Compute ++x → x becomes 2 → nonzero → left operand of || is true.Since left of || is true, the right-hand expression (++y && ++z) is not evaluated.The value of the overall expression is 1 (true), so z is assigned 1.Final values: x = 2, y = 1, z = 1.
Verification / Alternative check:Parenthesize explicitly as z = (++x) || ((++y) && (++z)); and manually simulate short-circuiting to reach the same result.
Why Other Options Are Wrong:x=2, y=2, z=1 or z=2: would require evaluating ++y or ++z, which does not occur.x=1, y=2, z=1: contradicts ++x being evaluated first.
Common Pitfalls:Misremembering precedence between && and ||; forgetting that short-circuiting stops evaluation of the rest of the expression.
Final Answer:x=2, y=1, z=1