3

In the program shown below, prefix should be evaluated first because it has higher precedence, But answer is -2, 2, 0, 1 and it is explained in book "as LHS of || is true RHS is not evaluated."
Why is it so? All the increments should performed first and then logical should be checked because of precedence.

#include<stdio.h>

int main()
{
    int i=-3, j=2, k=0, m;
    m = ++i || ++j && ++k;
    printf("%d, %d, %d, %d\n", i, j, k, m);
    return 0;
}
WedaPashi
  • 3,561
  • 26
  • 42
codeluv
  • 305
  • 1
  • 15

3 Answers3

7

Don't get confused with Precedence and Order of evaluation.

The order of evaluation of logical OR || is left to right.

So if left = true then left || right will never execute right. In your code exactly same happened.

As you know, any non zero value treated as true in C, hence, ++i or -2 is true. So,

 m = ++i || ++j && ++k;
 m = true || bla bla bla; //right not even checked!
 m = true 
 m = 1

And you get the output as expected.

mazhar islam
  • 5,561
  • 3
  • 20
  • 41
  • 1
    so according to your answer precedence has no role to play in above answer?@rakeb – codeluv Jul 03 '15 at 05:22
  • Please read the answer carefully, of course precedence matter, but the order of evaluation is first thing you have to consider. As the LHS is true, the RHS will not evaluated at all. Means, `++j && ++k;` are not going to execute and increment their values. When any line/block of code evaluated then the question comes about their precedence. – mazhar islam Jul 03 '15 at 05:29
3

The logical && and || operators fully evaluate the LHS before doing any evaluation of the RHS.

In the code shown, since ++i is -2, the LHS of the || evaluates to true (1) and the RHS is not evaluated. Therefore, neither j nor k is incremented. The printed result follows: m was assigned 1, i became -2, and j stayed as 2 and k stayed as 0.

The only remaining issue is that && binds tighter than ||, so:

a || b && c

is equivalent to:

a || (b && c)

so if a evaluates to true (non-zero), then neither b nor c is evaluated.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
0

Operator precedence is a completely different thing. Order of evaluation is determined by side effects and sequence points.

see this manual on order of evaluation.

Raman
  • 2,735
  • 1
  • 26
  • 46