postincrement i ++什么时候执行?

bob*_*obo 3 c++ post-increment

可能重复:
未定义的行为和序列点

在机器代码级别的C++中,postincrement ++运算符何时执行?

所述优先级表表示后缀++运算符是2级:这意味着在

int x = 0 ;
int y = x++ + x++ ;  // ans: y=0
Run Code Online (Sandbox Code Playgroud)

后缀++ 首先执行.

但是,这条线的逻辑运算似乎是首先添加(0 + 0),但是这是怎么回事?

我想象的是以下内容:

// 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.
Run Code Online (Sandbox Code Playgroud)

所以,另一种选择是虽然x + x在x + x的优先级表上更高,但是由于x ++而生成的代码被插入加法运算的下方

// Option 2:  turn this into
int y = x + x ; // 
x++ ;
x++ ;
Run Code Online (Sandbox Code Playgroud)

第二个选项似乎更有意义,但我对此处的操作顺序感兴趣.具体来说,x何时改变

sha*_*oth 7

这个

int y = x++ + x++ ;
Run Code Online (Sandbox Code Playgroud)

是未定义的行为.任何事情都可能发生,包括一些不合理的结果,程序崩溃或其他任何事情.只是不要这样做.


Dav*_*eas 7

我将讨论以下非常好的示例,而不是跳过UB示例的细节:

int a = 0, b = 0;
int c = a++ + b++;
Run Code Online (Sandbox Code Playgroud)

现在,运算符的优先级意味着最后一行等效于:

int c = (a++) + (b++);
Run Code Online (Sandbox Code Playgroud)

并不是:

int c = (a++ + b)++; // compile time error, post increment an rvalue
Run Code Online (Sandbox Code Playgroud)

另一方面,后增量的语义相当于两个单独的指令(从这里开始只是一个心理图片):

a++; // similar to: (__tmp = a, ++a, __tmp) 
     // -- ignoring the added sequence points of , here
Run Code Online (Sandbox Code Playgroud)

也就是说,原始表达式将被编译器解释为:

auto __tmp1 = a;         // 1
auto __tmp2 = b;         // 2
++a;                     // 3
++b;                     // 4
int c = __tmp1 + __tmp2; // 5
Run Code Online (Sandbox Code Playgroud)

但只要满足以下约束条件(必须在之前或之前执行的x>y方法),编译器才允许重新排序5条指令:xyxy

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
Run Code Online (Sandbox Code Playgroud)

执行不同指令的顺序没有其他约束,因此以下是所有有效序列:

1, 2, 3, 4, 5
1, 2, 5, 3, 4
1, 3, 2, 4, 5
...
Run Code Online (Sandbox Code Playgroud)