Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logical Operators and their precedence in C/C++

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

like image 766
Desert Ice Avatar asked Nov 10 '12 12:11

Desert Ice


People also ask

What is the order of precedence for logical operators?

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.

Which operator has lowest precedence in C?

4) Comma has the least precedence among all operators and should be used carefully For example consider the following program, the output is 1.


2 Answers

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.

like image 69
Daniel Fischer Avatar answered Oct 06 '22 09:10

Daniel Fischer


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.

like image 32
MByD Avatar answered Oct 06 '22 11:10

MByD