Evaluate short-circuit and precedence for logical operators in C. What is printed?\n\n#include<stdio.h>\nint main()\n{\n int x, y, z;\n x = y = z = 1;\n z = ++x || ++y && ++z;\n printf("x=%d, y=%d, z=%d\n", x, y, z);\n return 0;\n}\n\nAssume standard operator precedence (&& before ||) and short-circuit evaluation.

Difficulty: Medium

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

More Questions from Control Instructions

Discussion & Comments

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