-7
int i=-3, j=2, k=0, m; 
m = ++i || ++j && ++k; 
printf("%d, %d, %d, %d\n", i, j, k, m);

Since ++ has more precedence than || and && in C, they are evaluated first and therefore the expression becomes m = -2 || 3 && 1. Now you can apply short circuiting but that produces incorrect answer. Why is that?

Shahbaz
  • 46,337
  • 19
  • 116
  • 182

2 Answers2

4

Precedence ≠ order of evaluation.

The short-circuiting behavior of || and && means that their left-hand sides are evaluated first, and

  • If the LHS of || evaluates to true (nonzero), the RHS is not evaluated (because the expression will be true no matter what the RHS is)
  • If the LHS of && evaluates to false (or zero), the RHS is not evaluated (because the expression will be false no matter what the RHS is)

In your example, ++i gets evaluated, and is equal to -2, which is nonzero, so the right-hand side of the || (that is, ++j && ++k) never gets evaluated: j and k are never incremented.

dan04
  • 87,747
  • 23
  • 163
  • 198
1

The ++s don't execute before the expression. Only ++i executes, which indicates that the result of the expression will be 1, therefore the rest of the expression is not evaluated (short circuit).

Your code is equivalent to:

if (++i)
    m = 1;
else
    if (!++j)
        m = 0;
    else if (!++i)
        m = 0;
    else
        m = 1;

This means that once ++i is evaluated to true, the else part is never executed.

Shahbaz
  • 46,337
  • 19
  • 116
  • 182