I was recently came across a piece of code
// Program to overcome division by zero
int a=0;
int b=100;
int c= a==0 || b/a ;
printf("Hello");
//Output : Hello
My theory:
According to the precedence, operator / has higher precedence than ||. So b/a must get executed first and we should get a run time error.
I assume what is happening though is :
short-circuit operator || , evaluates the LHS a==0, which is true and hence does not execute b/a.
Is my theory wrong?. I am pretty sure this is something very simple that i just can’t figure out right now
Precedence doesn’t imply evaluation order, only grouping (parentheses).
There is a sequence point (old parlance) after the evluation of the first operand of the
||, so the first operand of||must be evaluated before the second, regardless of what these operands are. Since in this case the overall result of the expressiona == 0 || b/awas determined by the first operand, the second isn’t evaluated at all.