I know the below code will lead to undefined behaviour according to c/c++ standard but what about in c#? ,After some searching I found that in c# all the arguments/variables in an expression are evaluated from left to right(please correct me if am wrong), If this is true than the result(output of res variable) of below program should be 3, but its 4 ??.
class Program
{
static void Main(string[] args)
{
int a = 1;
int res = (a++) + (++a); //Will This Lead to Undefined Behavior(Like in C/C++)..??
Console.WriteLine(res);
Console.ReadLine();
}
}
The result is fine for these expressions when checked with left to right evaluation.
res = a + ++a; \\Successfully evaluates res to 3
res = ++a + a; \\Sussessfully evaluates res to 4
res = ++a + a++; \\Successfully evaluates res to 4
Similarly
res= a++ + ++a ;\\should be 3, why i get it 4 ??
Can Anybody explain am confused.??
Your program is equivalent to:
var a = 1;
var temp0 = a++;
var temp1 = ++a;
var res = temp0 + temp1;
And the result of that is 4
.
Even simpler:
var a = 1;
var temp0 = a; a++;
a++; var temp1 = a;
var res = temp0 + temp1;
C# does not have Undefined Behavior like C/C++. That would undermine the security properties of .NET. That said .NET can and does have implementation defined behavior in a few places. Not here, though.