问题描述
代码级别,postincrement ++运算符何时被执行?
In C++ on a machine code level, when does the postincrement++ operator get executed?
表示后缀++运算符是2级:这意味着
The precedence table indicates that postfix++ operators are level 2: which means in
int x = 0 ;
int y = x++ + x++ ; // ans: y=0
后缀++的第一个执行 >
The postfix ++'s execute first.
但是,这行的逻辑操作似乎是第一次发生的加法(0 + 0),但是如何发生呢?
However, it would seem that the logical operation of this line is the addition happens first (0+0), but how does that happen?
我想象的是以下内容:
// Option 1:
// Perform x++ 2 times.
// Each time you do x++, you change the value of x..
// but you "return" the old value of x there?
int y = 0 + x++ ; // x becomes 1, 0 is "returned" from x++
// do it for the second one..
int y = 0 + 0 ; // x becomes 2, 0 is "returned" from x++... but how?
// if this is really what happens, the x was already 1 right now.
因此,另一个选项是虽然x ++在x + x的优先级表上更高,由于x ++插入添加操作
So, the other option is although x++ is higher on the precedence table that x + x, the code generated due to x++ is inserted below the addition operation
// Option 2: turn this into
int y = x + x ; //
x++ ;
x++ ;
第二个选项似乎更有意义,但我对这里的操作顺序感兴趣。具体来说,何时更改?
That second option seems to make more sense, but I'm interested in the order of operations here. Specifically, when does x change?
推荐答案
UB,我将讨论以下完全精确的示例:
Instead of jumping on the details of the example that is UB, I will discuss the following example that is perfectly fine:
int a = 0, b = 0;
int c = a++ + b++;
现在,运算符的优先级意味着最后一行等效于:
Now, the precedence of operators means that the last line is equivalent to:
int c = (a++) + (b++);
而不是:
int c = (a++ + b)++; // compile time error, post increment an rvalue
另一方面,post增量的语义相当于两个单独的指令(从这里只是一个心理图片):
On the other hand, the semantics of the post increment are equivalent to two separate instructions (from here on is just a mental picture):
a++; // similar to: (__tmp = a, ++a, __tmp)
// -- ignoring the added sequence points of , here
也就是说,编译器将原始表达式解释为:
That is, the original expression will be interpreted by the compiler as:
auto __tmp1 = a; // 1
auto __tmp2 = b; // 2
++a; // 3
++b; // 4
int c = __tmp1 + __tmp2; // 5
但是编译器允许重新排序5个指令,只要满足以下约束( x> y
表示 x
必须在 y
或 x
之前 y
):
But the compiler is allowed to reorder the 5 instructions as long as the following constraints are met (where x>y
means x
must be executed before y
, or x
precedes y
):
1 > 3 // cannot increment a before getting the old value
2 > 4 // cannot increment b before getting the old value
1 > 5, 2 > 5 // the sum cannot happen before both temporaries are created
执行不同的指令,因此以下都是有效的序列:
There are no other constraints in the order of execution of the different instructions, so the following are all valid sequences:
1, 2, 3, 4, 5
1, 2, 5, 3, 4
1, 3, 2, 4, 5
...
这篇关于什么时候postincrement i ++得到执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!