C short-circuiting with pre-increment side effects: what does this program print? #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, 3, 0, 1

Explanation:

Introduction / Context:This problem blends operator precedence (&& before ||), short-circuit evaluation, and side effects of the pre-increment operator. Mastering the order of evaluation and when increments occur is essential for correct reasoning about C expressions.

Given Data / Assumptions:

  • Initial values: i = -3, j = 2, k = 0.
  • Expression: m = (++i && ++j) || ++k due to precedence.
  • Short-circuit rules: stop evaluating && on false left; stop evaluating || on true left.

Concept / Approach:Evaluate ++i, then ++j only if needed by &&, and ++k only if the left side of || is false. Nonzero values count as true. Carefully track variable updates as you go.

Step-by-Step Solution:

++i: i goes from -3 to -2 → true (nonzero).Because left of && is true, evaluate ++j: j becomes 3 → true.true && true → true, so left side of || is true.Since the left of || is true, ++k is not evaluated; k remains 0.Thus m = 1. Final values: i = -2, j = 3, k = 0, m = 1.

Verification / Alternative check:Insert prints after each step or separate the expression into temporaries to see the same final state, confirming short-circuit behavior prevents ++k from executing.

Why Other Options Are Wrong:

Any option where k = 1 assumes ++k executed, but it did not due to || short-circuit.Option b shows i unchanged; ++i must execute first.Option a changes i incorrectly and leaves j unchanged.

Common Pitfalls:Forgetting precedence and imagining left-to-right increments without considering short-circuit; assuming negative values are false (they are true if nonzero).

Final Answer:-2, 3, 0, 1.

More Questions from Expressions

Discussion & Comments

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