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?

22nd Feb 2019, 10:52 PM
Adrian Grill
Adrian Grill - avatar
5 Réponses
+ 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
22nd Feb 2019, 10:58 PM
Pedro Tortello
Pedro Tortello - avatar
+ 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
23rd Feb 2019, 6:26 AM
Anna
Anna - avatar
+ 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++.
23rd Feb 2019, 8:42 AM
David Carroll
David Carroll - avatar
+ 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. :)
22nd Feb 2019, 10:57 PM
HonFu
HonFu - avatar
0
Yeah I stumbled on this in one of challanges and honestly I got stupid
22nd Feb 2019, 10:59 PM
Adrian Grill
Adrian Grill - avatar