[英]Operator precedence of ++ and &&
I have the following code 我有以下代码
int a=0,b=5;
int c=a&&++b;
cout<<b;
When I run this snippet, the output value is 5
. 当我运行此代码段时,输出值为
5
。
From my understanding, ++
has a greater operator precedence, and so shouldn't ++b
be evaluated before the &&
leading to the value of b
to be 6
? 据我了解,
++
具有更大的运算符优先级,因此++b
不应在&&
导致b
的值为6
之前求值吗?
Why does the value in b
not get incremented? 为什么
b
中的值不增加? Is it because I misunderstood the precedence or some other feature? 是因为我误解了优先顺序或其他功能吗?
Precedence isn't what matters here. 优先级在这里并不重要。
&&
does short circuit evaluation, so first its left operand is evaluated. &&
短路评估,因此首先评估其左操作数。 Then if and only if that is non-zero, its right operand is evaluated. 然后,当且仅当该值非零时,才对其右操作数求值。
In your case, its left operand is zero, so its right operand isn't evaluated. 在您的情况下,其左操作数为零,因此不评估其右操作数。 Thus,
++b
is never evaluated, so the value of b
isn't changed. 因此,
++b
不会被求值,因此b
的值不会改变。
You misunderstand what operator precedence means in the language. 您误解了运算符优先级在语言中的含义。 It does not define order of evaluation but rather how expression syntaxically parsed.
它不定义求值顺序,而是定义如何语法分析表达式。
Let's look into expression: 我们来看一下表达式:
*ptr++ = b + c / d;
operator precedence means that it compiled as: 运算符优先级意味着它编译为:
( *(ptr++) ) = ( b + ( c / d ) );
not: 不:
( *( (ptr++) = b ) + c ) / d;
or something like this. 或类似的东西。 But it does not define in which order they evaluated directly.
但是它并没有定义他们直接评估的顺序。
So back to original: 回到原始:
( *(ptr++) ) = ( b + ( c / d ) );
in this case we have operator=
which requires output of operator*
and output of operator+
so those operators have to be evaluated before assignment, operator+
requires output of operator/
so operator/
has to be evaluated before operator+
and so on. 在这种情况下,我们有
operator=
需要的输出operator*
和输出operator+
到分配前进行评估,以便那些运营商有, operator+
要求的输出operator/
所以operator/
拥有待评估之前operator+
等。 But because operator*
has higher precedence than operator+
does not mean it will be evaluated first in this case. 但是,因为
operator*
优先级高于operator+
,并不意味着在这种情况下将首先对其进行评估。 It's up to compiler to decide as there is no direct dependencies between them. 由于它们之间没有直接的依赖关系,由编译器决定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.