+ 2

Quick question about C++

Quick question, I have this code: "#include <iostream> using namespace std; int main(){ int m=2,n=6; int &x=m; int &y=n; m=x++; x=m++; n=y++; y=n++; cout<<m<<n; }" Which outputs "26." Why is this? m was assigned to x and x incremented which means it should now equal 3. Then x was assigned to m and m incremented which means m should now equal 3. So in the end, the output should be 36, right?

19th Jun 2017, 3:58 PM
21kHzBANK21kHZ
21kHzBANK21kHZ - avatar
1 Odpowiedź
+ 6
In C++, doing var = var++; does nothing. It doesn't change the value of the variable. The reason is because the variable is assigned to back to itself, and then the previous instance of the variable is incremented, but not the value held by the existing variable. However, this isn't the case with Java (and probably a couple more languages with postfix/prefix increment operators).
19th Jun 2017, 5:01 PM
Hatsy Rei
Hatsy Rei - avatar