运算符优先级和评估顺序 [英] Operator precedence and evaluation order

查看:69
本文介绍了运算符优先级和评估顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解这个程序的输出:

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;
}

输出:

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 将评估为 true ,因此不会评估 ++x .

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

推荐答案

优先级"影响分组,而不是顺序,这意味着如果操作数属于"哪个运算符存在任何歧义,则具有更高的运算符优先权首先得到它.

"Precedence" affects grouping, not order, and means that if there could be any ambiguity regarding which operator an operand "belongs to", the operator with the higher precedence gets first dibs on it.

由于涉及到两个二元运算符,因此您可以通过两种方式读取表达式.
作为树木,这些将是:

Since there are two binary operators involved, there are two ways you can read the expression.
As trees, these would be:

    and
    /\
   or ++z       [(++x || ++y) && ++z]
  / \
++x ++y 


   or
   /\
++x  and       [++x || (++y && ++z)]
     / \
  ++y ++z

优先规则决定在 C++ 中选择后一棵树,因为中间操作数 ++y&& 分组,而不是与 <代码>||.

The precedence rules determine that the latter tree is chosen in C++, since the middle operand, ++y, is grouped with &&, not with ||.

这些运算符的短路"意味着评估必须从最左边的叶子开始(每个运算符必须首先评估它的左腿,如果需要,然后再评估它的右腿).
因此,首先评估 ++x,并且 || 仅在 ++x 为零时才继续其右腿,它不是'

The "short-circuiting" of these operators means that evaluation must start at the leftmost leaf (each operator must first evaluate its left leg, then its right if it needs to).
Thus, ++x is evaluated first, and || only continues with its right leg if ++x is zero, which it isn't.

(从精彩绝伦的图解可以看出,++x必须先求值,而不管&&的相对优先级如何||.)

(As can be seen from the wonderful and artistic diagrams, ++x must be evaluated first regardless of the relative precedence of && and ||.)

这篇关于运算符优先级和评估顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆