Search code examples
cpre-increment

Increment and logical operators precedence


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;
}

Solution

  • 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.