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
The order of precedence is: logical complements ( not ) are performed first, logical conjunctions ( and ) are performed next, and logical disjunctions ( or ) are performed at the end. Notice: You can always use parentheses to change the default precedence.
4) Comma has the least precedence among all operators and should be used carefully For example consider the following program, the output is 1.
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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With