0
Pls explain this decrementation (C#)
Please explain why output of this code is 3 and not 2 ;-; int a = 3; int b = 10; int z = a + b % --a; Console.WriteLine(z); // 3 Shouldn't 'a' be decremented in all places in the 'z' declaration? How does that work?
5 Answers
+ 4
The first "a" will return the value "3".
Then "--a" decreases the value of "a" before the operation, so it has the value "2".
a + b % --a
3 + 10 % 2
3 + 0
z = 3
+ 8
I don't know about undefined behavior in C#, but if you run the same code in C or C++, the result will be 2 (on Sololearn). I'd take that as a warning not to use such expressions. The least you can say is that if at some point you need to translate your code from C# to C or C++, you might evoke undefined behavior without realizing
+ 6
Anna Many C# developers who later learn C++ will be surprised by the undefined behaviors with sequence point and accessing array indexes out of range.
In C#, the order of evaluations are explicitly determined left to right. In C and C++, the order of evaluations are unspecified and undefined where a sequence point is ambiguous.
TL;DR... What you described for C++ isn't an issue in C#. đ
And I do agree... this could be a challenge when porting from C# to C++.
+ 4
In C you're not supposed to use & increment a variable in the same statement because compiler-wise it's not defined in what order it will be executed -> undedined behaviour
I'm excited to hear from C# people if the issue is the same. :)
0
Yeah I stumbled on this in one of challanges and honestly I got stupid