user3531168
user3531168

Reputation: 309

C++: Post-Increments resulted in the same value

The following of post-increments will result as follows:

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 resulted in n = 1 and not n = 3?

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

If the code was done with pre-increment of n (++n), the result is n = 4 which is to be expected. I know the second code segment should never be done like that in the first place but it is something that I came across and I was curious as to why it resulted like that.

Please advise.

Upvotes: 4

Views: 162

Answers (3)

Laura Maftei
Laura Maftei

Reputation: 1863

Other examples from C++11 standard include:

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

Upvotes: 3

Richard Hodges
Richard Hodges

Reputation: 69854

The other answers explain correctly that this code results in undefined behaviour. You may be interested as to why the behaviour is as you see it on your compiler.

As far as most compilers are concerned the expression x = n++ will be compiled into the following fundamental instructions:

  1. take a copy of n, call it n_copy;
  2. add 1 to n
  3. assign n_copy to x

Therefore the expression n = n++ becomes:

  1. take a copy of n, call it n_copy;
  2. add 1 to n
  3. assign n_copy to n

Which is logically equivalent to:

  1. assign n to n

Which is logically equivalent to:

  1. do nothing.

That's why in your case you see n == 1. Not all compilers will necessarily produce the same answer.

Upvotes: 1

dynamic
dynamic

Reputation: 48091

Your second example is not allowed and has an undefined behaviour. You should use a temporary variable if you need something like that. But hardly you need something like that.

Quoting Wikipedia:

Since the increment/decrement operator modifies its operand, use of such an operand more than once within the same expression can produce undefined results. For example, in expressions such as x − ++x, it is not clear in what sequence the subtraction and increment operators should be performed. Situations like this are made even worse when optimizations are applied by the compiler, which could result in the order of execution of the operations to be different from what the programmer intended.

Upvotes: 10

Related Questions