Logical operators and their priority in C / C ++

I recently came across a piece of code

// Program for overcoming division by zero

int a=0; int b=100; int c= a==0 || b/a ; printf("Hello"); 

// Output: Hello

My theory: According to priority, the / operator has higher priority than ||. So b / a must first execute, and we should get a runtime error.

I guess what happens, although there are:

short circuit operator ||, evaluates LHS a == 0, which is true and therefore does not execute b / a.

Is my theory wrong? I'm sure this is something very simple that I just can’t understand right now

+4
source share
2 answers

Priority does not imply an evaluation order, but only a grouping (parentheses).

After defining the first operand || there is a sequence point (old language), so the first operand || must be evaluated to the second, regardless of what these operands are. Since in this case the general result of the expression a == 0 || b/a a == 0 || b/a determined by the first operand, the second was not evaluated at all.

+8
source

Higher priority / over || means that the expression evaluates to:

 int c= (a==0) || (b/a) ; 

And not

 int c= (a==0 || b)/a ; 

But still, since the logical estimate is short-circuited, b/a will be evaluated only if a!=0 .

+3
source

Source: https://habr.com/ru/post/1445213/


All Articles