Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# in a nutshell example misunderstanding ++ unary operator increment [duplicate]

I am reading C# 5.0 in a nutshell and I have the following statements:

int x = 0;

while (true)
{
    if (x++ > 5)
        break ;      // break from the loop
}
x.Dump();

Executing the statements on LINQPad 4 the output is 7.

I still don't understand WHY?. Why it is not 6 being the condition: x++>5

like image 448
Carlos Landeras Avatar asked Nov 27 '22 21:11

Carlos Landeras


2 Answers

The ++ operator increments the value and returns the original value.

So when x was 5, x was incremented and the condition 5 > 5 is evaluated.

Then, when x was 6, x was incremented and the condition 6 > 5 is evaluated, which results in the break. Because x was still incremented, the value of x in the end is 7.

People often say that when the ++ operator is use as a postfix, the increment is executed after the comparison, but this is not technically true, which is shown by decompilation in LinqPad:

int x = 5;
if (x++ > 5) 
Console.WriteLine(x);

IL:

IL_0001:  ldc.i4.5    
IL_0002:  stloc.0     // x
IL_0003:  ldloc.0     // x
IL_0004:  dup         
IL_0005:  ldc.i4.1    
IL_0006:  add         // <---- Increment
IL_0007:  stloc.0     // x <-- Result of increment is popped from the stack and stored in a variable
IL_0008:  ldc.i4.5    
IL_0009:  cgt         // <---- Comparison
IL_000B:  ldc.i4.0    
IL_000C:  ceq         
IL_000E:  stloc.1     // CS$4$0000
IL_000F:  ldloc.1     // CS$4$0000
IL_0010:  brtrue.s    IL_0019
IL_0012:  ldloc.0     // x
IL_0013:  call        System.Console.WriteLine
like image 57
Rik Avatar answered Dec 06 '22 13:12

Rik


x++ > 5 means check the value of x against 5 then increment it. Which means your break is not reached until x == 7.

The result would be 6 if you used ++x, i.e. increment x and then test it against 5.

like image 43
CodingIntrigue Avatar answered Dec 06 '22 14:12

CodingIntrigue