It is the priority of the operator ignored in the if conditions

I'v the following code:

void main() { int k, x, y, z; printf("\nExperiment 1:"); x = 0, y = 0, z = 0; k = x++ || y++ && z++; printf("\nx = %d, y = %d, z = %d and k = %d\n", x, y, z, k); printf("\nExperiment 2:"); x = 1, y = 0, z = 0; k = x++ || y++ && z++; printf("\nx = %d, y = %d, z = %d and k = %d\n", x, y, z, k); } 

Exit:

Experiment 1: x = 1, y = 1, z = 0 and k = 0 Experiment 2: x = 2, y = 0, z = 0 and k = 1

I realized: For the expression to be true, either to the left or to the right of '||' must be nonzero. It starts on the left. If left is not equal to zero, it is not evaluated additionally. If it is zero, it starts on the right side. On the right we have && '. So, we start again on the left side of && and if it is zero, the expression cannot be true, and it does not continue. Otherwise, he evaluates the right side of '& &'

My guess was the operator && has a higher priority. So, both of his arguments should be evaluated, and then && should have been applied over it, followed by the evaluation of both arguments ||.

Does the compiler optimize itself? I used Visual Studio TC compatible with disabled optimization.

+7
source share
2 answers

I think this is described in C11 on ยง6.5.14 Logical OR operator (my emphasis)

Unlike bitwise | operator, || operator warranty rating from left to right ; if the second operand is evaluated, a point in the sequence between the evaluations of the first and second operands. If the first operand is not equal to 0, the second operand is not evaluated.

+9
source

So the expression

 k = x++ || y++ && z++; 

interpreted as (due to evaluation rules):

 k = x++ || (y++ && z++); 

In experiment 1, we have x = y = z = 0; .

In experiment 2, we have x = 1, y = z = 0; .

So, the expression on the right-hand side stops after evaluating y++ , since the value of this is 0 and, therefore, is logical and cannot become true.

+4
source

All Articles