Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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.

like image 548
user3531168 Avatar asked Dec 08 '22 06:12

user3531168


2 Answers

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.

like image 136
dynamic Avatar answered Dec 10 '22 19:12

dynamic


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
like image 27
Laura Maftei Avatar answered Dec 10 '22 19:12

Laura Maftei