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:
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
float a = 0.7;
, what will this program print and why?
#includefor
loop in C. What does this program print?
#includeswitch
statement in C? Note the statement before any case
label.
#include
Discussion & Comments