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 expression a == 0 || b/a
a == 0 || b/a
was determined by the first operand, the second isn't evaluated at all.
The higher precedence of /
over ||
means that the expression is evaluated as:
int c= (a==0) || (b/a) ;
And not
int c= (a==0 || b)/a ;
But still, as the logical evaluation is short-circuited, b/a
will only be evaluated if a!=0
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.