C ++: Post-increments led to the same value

The following subsequent increments will look like this:

n = 1;
j = n++;  //j = 1, n = 2
j = n++;  //j = 2, n = 3
j = n++;  //j = 3, n = 4

My question is why the following led to n = 1, rather than n = 3?

n = 1;
n = n++;  //n = 1
n = n++;  //n = 1
n = n++;  //n = 1

If the code was executed with a preliminary increment n( ++n), the result will be n = 4what should be expected. I know that the second segment of code should never be done as it was in the first place, but this is what I came across, and I was curious why this happened.

Please inform.

+4
source share
3 answers

Other answers correctly explain that this code leads to undefined behavior. You may be wondering why the behavior is what you see on your compiler.

, x = n++ :

  • n, n_copy;
  • 1 n
  • n_copy x

n = n++ :

  • n, n_copy;
  • 1 n
  • n_copy n

:

  • n n

:

  • .

n == 1. .

+1

undefined. , - . - .

Wikipedia:

increment/decment , undefined. , , x - ++ x, , . , , , .

+10

++ 11 :

i = v[i++]; // the behavior is undefined
i = 7, i++, i++; // i becomes 9
i = i++ + 1; // the behavior is undefined
i = i + 1; // the value of i is incremented
f(i = -1, i = -1); // the behavior is undefined
+3

All Articles