This question already has an answer here:
- Undefined behavior and sequence points 5 answers
#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int n = 5;
cout<< n++ <<" "<< ++n << " "<< n++;
_getch();
return 0;
}
When I run this program on Visual Studio the output is 7 8 5.
I think it is compiler dependent. ( Correct me if I am wrong) But shouldn't it be either 7 7 5 or 5 7 7 ?
The sequence, in which the various n++ / ++n are executed, is undefined by the C standard and might change over time or depending on target machine and/or optimization options. However, I think, a compiler SHOULD still create code, that executes each of the n++ or ++n in an atomic fashion. So, if Visual Studio apparently starts with the n++ at the end (as can be seen from the "5" in the result), then it should create either 7 7 5 or 6 8 5 as result, depending on whether it executes the n++ in front or the ++n in the middle as second term.
But G++ also produces 7 8 5. When I look at the assembly code, the reason seems to be, that G++ does all the increments in strict order from right to left, but also aliases "++n" with "n" later. This can be seen more clearly from this code:
int n = 2;
cout << n++ << " " << ++n << " " << n++ << " " << ++n << " " << n++;
The result is 6 7 4 7 2
. So apparently, in case of n++
, the compiler creates a "snapshot" of n
before the increment, while in case of ++n
, the compiler just does the increment and later just uses the current value of n, when it is written to cout.
Of course, the result of having two increments to the same value is undefined, so the compiler's choice is completely legal.
来源:https://stackoverflow.com/questions/18174498/how-is-the-postfix-and-prefix-increment-operator-evaluated-in-an-expression