C# in a nutshell example misunderstanding ++ unary operator increment

c#, loops, while-loop

Solution

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

Problem

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

Original source

Related problems