Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is the precedence of operator ignored in 'if' conditions

I'v a 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);
}

The output:

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

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

What I've understood is: For the expression to be true, either left side or right side of '||' has to be non-zero. It starts from left. If left is non-zero, it doesn't evaluate further. If it is zero, it starts on right side. On right we have '&&'. So, we again start from left side of && and in case it is zero, the expression cannot be true and it doesn't proceed. Otherwise it evaluates the right side of '&&'

My assumption was operator && has higher precedence. So, both of its arguments should have been evaluated and then && should have been applied over it followed by evaluation of both arguments of ||.

Is compiler optimizing itself? I've used Visual Studio TC compilar with Optimization disabled.

like image 460
bugger Avatar asked May 17 '13 11:05

bugger


People also ask

What is the order of precedence of operators?

The logical-AND operator ( && ) has higher precedence than the logical-OR operator ( || ), so q && r is grouped as an operand. Since the logical operators guarantee evaluation of operands from left to right, q && r is evaluated before s-- .

What decides the order in which the operator with the same precedence are executed?

If consecutive operators in an expression have the same precedence, a rule called associativity is used to decide the order in which those operators are evaluated.

Where in C the order of precedence of operators does not exist?

Where in C the order of precedence of operators do not exist? Explanation: None.


1 Answers

I think this is covered in C11 by §6.5.14 Logical OR operator (my emphasis)

Unlike the bitwise | operator, the || operator guarantees left-to-right evaluation; if the second operand is evaluated, there is a sequence point between the evaluations of the first and second operands. If the first operand compares unequal to 0, the second operand is not evaluated.

like image 122
simonc Avatar answered Sep 23 '22 03:09

simonc