So I was reading about the order of different operators, and I read that &&
has higher importance than ||
and it would evaluate sooner (source). Then somebody asked a question about what this piece of code would print:
#include <stdio.h>
int main(){
int a=0, b=0, c=0, d=0;
if(a++>0 || ++b==1 || c--<=0 && d++>c--){
printf("if\na:%d\nb:%d\nc:%d\nd:%d\n",a,b,c,d);
}
else{
printf("else\na:%d\nb:%d\nc:%d\nd:%d\n",a,b,c,d);
}
return 0;
}
And I thought that the c-- <= 0 && d++ > c--
would evaluate first, which is true in total. after the process, c
would be equal to -2 and d
would be equal to 1. Then it would start checking from the left side, evaluating a++ > 0 || ++b == 1
which is true, a
would be 1 at the end and b
is 1 in the condition and after that. so the total condition would be true || true
and it is true, so we will print:
if
a:1
b:1
c:-2
d:1
Yes? Apparently, no. I've tested it with GCC (Mingw) on my system (Windows 10), and with an online compiler (this one) and both printed:
if
a:1
b:1
c:0
d:0
I've changed the condition into this: if(a++>0 || ++b==1 || (c--<=0 && d++>c--) )
but the output is the exact same thing on both places. Is there something that I don't pay attention to? Or is this something like a bug? It almost looks like that ||
and &&
have the same priority and the whole thing is evaluated from the left side, and short-circuits occurs and other things. If I change the ++b==1
part into ++b==0
, then the output is the same as I predicted.
Thanks in advance for any kind of help :)