Operator precedence and evaluation order

前端 未结 5 2182
梦如初夏
梦如初夏 2021-02-09 05:37

I can\'t understand output of this program:

#include
using namespace std;
int main()
{
    int x = 1 , y = 1, z = 1;
    cout << ( ++x || +         


        
5条回答
  •  孤城傲影
    2021-02-09 06:29

    && 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||).

提交回复
热议问题