Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator precedence and evaluation order

I can't understand output of this program:

#include<iostream>
using namespace std;
int main()
{
    int x = 1 , y = 1, z = 1;
    cout << ( ++x || ++y && ++z ) << endl; //outputs 1;
    cout << x << " " << y << " " << z ;  //x = 2 , y = 1 , z = 1;
    return 0;
}

Output:

1
2 1 1

If || is evaluated first then this output is fine, however this article says that && has a higher precedence than ||, and thus it must be evaluated first. If this is the case then according to me output should be:

1
1 2 2

as ++y && ++z would evaluate to true and thus ++x won't be evaluated.

like image 995
shiva Avatar asked Aug 24 '16 14:08

shiva


2 Answers

Let's put the excess parantheses in:

( ++x || (++y && ++z ))

Then it's easy to see that (++y && ++z ) will only be evaluated if ++x is 0. So you can see that irrespective of operator precedence, the short-circutting nature of || means that the right hand side is only evaluated if the left hand side is 0.

(If the right hand side is evaluted, then note that ++z will only be evaluated if ++y is not 0.)

like image 139
Fitzwilliam Bennet-Darcy Avatar answered Sep 25 '22 06:09

Fitzwilliam Bennet-Darcy


&& has a higher precedence than ||, and thus it must be evaluated first.

No. Operator precedence only determines that how the operators will be bound tighter (as if by parentheses) to its arguments when parsing an expression, it doesn't influence evaluation order. In this case, it just means ++x || ++y && ++z will be parsed as (++x) || (++y && ++z), rather than (++x || ++y) && (++z).

Note that the associativity of operator|| is left-to-right, so ++x will be evaluated at first, and (++y && ++z) won't be evaluated because of short-circuit evaluation (other than overloaded operator||).

like image 24
songyuanyao Avatar answered Sep 24 '22 06:09

songyuanyao