Home > Mobile >  Confusion about operator precedence in C
Confusion about operator precedence in C

Time:06-27

I got bit confused by how to interpret the precedence of operators in the following snippet:

int a,b,c,d;
a=b=c=d=1;
a=  b>1 ||   c>1 &&   d>1

The values of a,b,c,d at the end of this code snippet are 1,2,1,1 respectively. I was trying to decipher what was happening here but to no avail.

I know the precedence of is higher than any other operators so why b,c, and d doesn't equal 2? According to the result I received, I guess that the expression was evaluated left to right when at the first step b is incremented to 2 therefore b>1 is true then because there is a logical OR the answer is returned immediately. Like if it was : ( b>1) || ( c>1 && d>1)

Does operator precedence have any other role other than to group operands together? What does it have to do with the order of execution for example?

CodePudding user response:

The reason is because of Short-circuit evaluation which means that the evaluation will stop as soon as one condition is evaluated true (counting from the left).

This:

a=  b>1 ||   c>1 &&   d>1

is therefore similar to this:

if(  b > 1) {
    a = true;
} else if(  c > 1) {
    if(  d > 1) {
        a = true;
    }
} 
  • Related