In a C program:
1 || 0 && 0 results in 1. I thought this behavior as the OR operator has short-circuited rest of the right side (0 && 0) because of 1 on the left side.
But
0 && 0 || 1 also results in 1. I am confused why 0 on the left side of AND operator has not short circuited 0 || 1 and the answer is not 0.
Please guide me!
CodePudding user response:
This has to do with operator precedence.
The logical AND operator has higher precedence than the logical OR operator ||. So this:
1 || 0 && 0
Parses as:
1 || (0 && 0)
And this:
0 && 0 || 1
Parses as:
(0 && 0) || 1
So in the latter case, first 0 && 0 is evaluated. This results in the value 0, so now you have 0 || 1. The left side of the OR is false so this causes the right side to be evaluated, causing the || operator to result in 1.
