In C, evaluate short-circuit and precedence: what is the output? #include<stdio.h> int main() { int i = -3, j = 2, k = 0, m; m = ++i || ++j && ++k; printf("%d, %d, %d, %d ", i, j, k, m); return 0; }

Difficulty: Medium

Correct Answer: -2, 2, 0, 1

Explanation:


Introduction / Context:
This question examines how C handles logical operator precedence (&& before ||) and short-circuit evaluation. Understanding which subexpressions are skipped is essential for predicting the final values and the printed output.


Given Data / Assumptions:

  • Pre-increment operators (++i, ++j, ++k) modify variables before they are used.
  • Operator precedence in C: && has higher precedence than ||.
  • Short-circuit rules: if the left operand of || is true, the right operand is not evaluated.


Concept / Approach:
Evaluate ++i first (left operand of ||). If this becomes nonzero (true), then the entire || expression is true without touching the right-hand side (++j && ++k). This freezes j and k at their prior values.


Step-by-Step Solution:
Start: i = -3, j = 2, k = 0.Compute ++i: i becomes -2, which is nonzero → true.Since left side of || is true, (++j && ++k) is not evaluated.Thus, j remains 2, k remains 0, and m is set to 1 (true).printf prints i, j, k, m → -2, 2, 0, 1.


Verification / Alternative check:
Insert printf statements before and after the expression to observe that j and k never change. Compiling with optimization does not alter the semantics here.


Why Other Options Are Wrong:
(a) Changes i to 2 incorrectly and shows j unchanged but not consistent with ++i from -3. (b) and (c) give incorrect truth values for m or wrong increments. (e) suggests j and k were incremented, which would not happen with short-circuiting.


Common Pitfalls:
Forgetting that ++i from -3 becomes -2 (still true), and thinking && is evaluated first then combined with || without short-circuit rules.


Final Answer:
-2, 2, 0, 1

Discussion & Comments

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