6或7?运算符优先级 - posfix ++和前缀++和+ [英] 6 or 7 ? operator priority - posfix ++ and prefix ++ and +
问题描述
这个我的代码
```
#include< ; iostream>
使用命名空间std;
int main(){
int d = 2;
cout<< ++ d + d ++;
}
```
vs 2017年的输出:6
其他IDE的输出(主要是):7
您对我的代码有什么看法?
#cpp #c ++ #operator #code #cplusplus
这是未定义的行为。根据C ++标准,在同一个子表达式中多次修改相同内存位置的任何语句的结果都是未定义的。
在C ++ 17标准中,这是在4.6第17段:
"除非另有说明,否则对各个算子的操作数和个别表达式的子表达式的评估是不合理的。 [注意:在程序执行期间不止一次评估的表达式中,不需要在不同的评估中对其子表达式进行排序和不确定的
顺序评估。 -end note]运算符操作数的值计算在运算符结果的值计算之前排序。如果内存位置(4.4)上的一个副作用
相对于同一内存位置上的另一个副作用或使用同一内存位置中任何对象的值进行的值计算未被排序,并且它们不可能并发(4.7),行为未定。
[注意:下一节对潜在的并发计算施加了类似但更复杂的限制。 -end note]"
这一段给出了一个特例:
" i = i ++ + i; //行为未定义"
你正在做的是同样的事情,你要修改d的值两次,首先是++ d,第二次是d ++。
Hi,
this my code
```
#include <iostream>
using namespace std;
int main(){
int d = 2;
cout << ++d+d++;
}
```
output at vs 2017 : 6
output at other IDE (mostly) : 7
What is your opinion about my code ?
#cpp #c++ #operator #code #cplusplusThis is undefined behaviour. The result of any statement that modifies the same memory location more than once in the same sub expression is, per the C++ standard, undefined.
In the C++17 standard, this is in 4.6 paragraph 17:
"Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced. [Note: In an expression that is evaluated more than once during the execution of a program, unsequenced and indeterminately sequenced evaluations of its subexpressions need not be performed consistently in different evaluations. —end note] The value computations of the operands of an operator are sequenced before the value computation of the result of the operator. If a side effect on a memory location (4.4) is unsequenced relative to either another side effect on the same memory location or a value computation using the value of any object in the same memory location, and they are not potentially concurrent (4.7), the behavior is undefined. [Note: The next section imposes similar, but more complex restrictions on potentially concurrent computations. —end note] "
This paragraph gave a particular example:
"i = i++ + i; // the behavior is undefined"
What you are doing is the same thing, where you are modifying the value of d twice, first in the ++d, the second in the d++.
这篇关于6或7?运算符优先级 - posfix ++和前缀++和+的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!