Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

order of evaluation of || and && in c

Tags:

c

If the precedence of && is greater than that of ||, shouldn't this code evaluate --b && ++c first, and thus the output should be 1 2 4 11. But here it seems to be short circuited to give 1 2 5 10. Please help!

int x;
int a=1,b=5,c=10;
x=a++||--b&&++c;
printf("%d %d %d %d\n",x,a,b,c);
return 0;
like image 497
Ashwyn Avatar asked May 23 '12 17:05

Ashwyn


2 Answers

shouldn't this code evaluate --b && ++c first

No Operator precedence doesn't affect evaluation order. It just means that

a++||--b&&++c

is equilvalent to

a++||(--b&&++c)

so it's still a++ that is evaluated first, and thus short-circuits the statement.

like image 112
Luchian Grigore Avatar answered Oct 02 '22 20:10

Luchian Grigore


Yes, && has higher precedence, but that only determines the grouping of the operands, not the order of evaluation. The base operation here is ||, which guarantees its right side is not evaluated if the left is true, regardless of what operations are on the right-hand side.

like image 45
Kevin Avatar answered Oct 02 '22 19:10

Kevin