Why z=z++, the result of z has not changed?

int z = 2;
z = z++;
cout<<z;//输出仍为2

In codeblocks, dev c++ the output is 2
, in VC the output is 3

why is that?

Answer: Different compilers implement the postfix ++ operator differently.

To answer succinctly:
if a=2;
a++ is to create a copy a'=2, add 1 to a, and return the copy a'.
++a is a plus 1, returns a.

So when z=z++, the ++ operator has a higher priority than the =, and what the ++ operator has to do is executed first.
First create z'=2, add 1 to z to 3, and prepare to return the copy z'. The suffix ++ has been executed, and only = is executed at this time, so that z with a value of 3 is assigned z', and finally z=2!

Different compilers implement ++ differently, making it do different things. In VC, the copy z' is not created, and the assignment statement is executed first, and then incremented by 1. So it will be different, that's the reason for different compilers.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325699419&siteId=291194637