Postfix increment operator bug? (No) #4828
-
Here is this operator: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/arithmetic-operators#postfix-increment-operator It says it will increment the value by 1, effective on next line, but it doesn't do it for me (.NET 5 is used): using static System.Console;
int i = 1;
i += i++ + 1;
WriteLine(i); It should write In C++ it works fine: #include <iostream>
int main()
{
int i = 1;
i += i++ + 1;
printf("%i\n", i);
} C++ prints |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 19 replies
-
This, iirc, is undefined behavior in C++. In C#, it is well-defined: It increments the value of int i = 1;
int tmp = i;
i = tmp + 1; // This is the ++
i = tmp + 1; // This is the += |
Beta Was this translation helpful? Give feedback.
-
Fwiw, this is undefined in c++. Compilers are free to return any result here (or crash if they want). In c# this is actually well defined code that will result in the same behavior always (modulo compiler bugs). |
Beta Was this translation helpful? Give feedback.
-
Here you find a good description: https://stackoverflow.com/questions/54674728/is-there-an-explanation-for-inline-operators-in-k-c-k-c/54677275#54677275 The expanded version of your code is: int i = 1;
int eval_i = i; //eval_i = 1
int incrementI = i++; //incrementI is 1 - but i is 2
i = eval_i + (incrementI + 1); //incrementI + (incrementI +1) = 1 + (1 + 1) = 3
System.Console.WriteLine(i); |
Beta Was this translation helpful? Give feedback.
-
Multiple persons have contributed many good and some better answers. Let me recap it here and then accept my own answer. The C# spec mentions that the
So in my example, if I put the actual values for the variables the expression Another good example would be this: int[] a = new int[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
int j = 0;
a[j] += j++ + 1; It would be Bonus: If I wrote something stupid, or something needs to be fixed, please let me know in the comments. |
Beta Was this translation helpful? Give feedback.
Multiple persons have contributed many good and some better answers. Let me recap it here and then accept my own answer.
First thing, to not mix up operator precedence and expression evaluation order. Expressions are evaluated from left-to-right. Check this comment by Eric Lippert:
https://stackoverflow.com/questions/54674728/is-there-an-explanation-for-inline-operators-in-k-c-k-c/54677275#comment96149488_54677275
The C# spec mentions that the
i
variable in this case is evaluated only once:https://www.ecma-international.org/wp-content/uploads/ECMA-334_5th_edition_december_2017.pdf
Check
12.18.3 Compound assignment
from page 214.