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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With