4

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

Carlos Landeras
  • 11,025
  • 11
  • 56
  • 82

9 Answers9

7

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
Rik
  • 28,507
  • 14
  • 48
  • 67
  • I am trying to find some documentation about the loop for and the original value returned after the increment. Could you show me some link? I can not find it – Carlos Landeras Jan 07 '14 at 13:51
  • See http://msdn.microsoft.com/en-us/library/36x43w8w.aspx – Rik Jan 07 '14 at 13:53
5

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.

CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
  • Great explanation. Thanks. Never had to used before de x++ – Carlos Landeras Jan 07 '14 at 13:42
  • Although effectively the same, and often explained this way, this is not entirely accurate. The increment is executed *before* the comparison, but the return value of the increment operation is the *original value*, before incrementing. – Rik Jan 07 '14 at 13:44
  • 1
    @Rik Technically correct (the best kind of correct!), but in terms of understanding the statement, this makes it a lot easier – CodingIntrigue Jan 07 '14 at 13:48
  • 1
    I appreciate the Futurama reference, but I do think it's important to be accurate with this sort of thing. If you're aiming for an easy explanation, you should be clear that it's a simplification. Use language like "You can think of it as if (...)" instead of "This is how it works" when it really doesn't. – Rik Jan 07 '14 at 14:05
  • I think that's a fair point. – CodingIntrigue Jan 07 '14 at 14:18
4

The following are the iterations of the loop:

  • x == 0 -> comparison returns false -> x increased to 1
  • x == 1 -> comparison returns false -> x increased to 2
  • x == 2 -> comparison returns false -> x increased to 3
  • x == 3 -> comparison returns false -> x increased to 4
  • x == 4 -> comparison returns false -> x increased to 5
  • x == 5 -> comparison returns false -> x increased to 6
  • x == 6 -> comparison returns true -> x increased to 7 -> if-block is entered and the loop is left

The last value of x, namely 7, will be output.

Note that the x++ operation modifies the value of x, after the comparison x > 5 is evaluated, but regardless of whether or not the comparison returns true and the if-block is entered.

O. R. Mapper
  • 20,083
  • 9
  • 69
  • 114
4

On C#, the ++ unary operator, when wrote after its operand (it can be either ++x or x++) executes itself after evaluations in the expression. That means:

  • When x is 5, the expression is gonna be evaluated as false (5 is not > than 5) and then increment it to 6.
  • Then, when x is 6, the expression is gonna be evaluated as true yes (6 is > than 5), but then it is gonna increment again, breaking when x is 7.
  • 1
    Although effectively the same, and often explained this way, this is not entirely accurate. The increment is executed before the comparison, but the return value of the increment operation is the original value, before incrementing. – Rik Jan 07 '14 at 13:45
  • @Rik, you're right! :) The only thing that **really** changes is the return value of the operation. – João Brant Sep 10 '18 at 22:48
3

The reason is that x++ will evaluate after the check. So when it finally gets to x == 6 the condition will be met (6 > 5) and then afterwards it will be incremented (to 7)

It is easier to explain with some alternate code, which will produce the same result:

while (true)
{
    if(x > 5)
    {
        //x = 6
        x++;
        //x = 7
        break;
    }
    x++;//x increments from 0 - 6, over 6 loops
}
musefan
  • 47,875
  • 21
  • 135
  • 185
  • Although effectively the same, and often explained this way, this is not entirely accurate. The increment is executed before the comparison, but the return value of the increment operation is the original value, before incrementing. – Rik Jan 07 '14 at 13:46
  • @Rik... Yes, I seen your comment coming ;-) – musefan Jan 07 '14 at 13:46
2

You're evaluating x before you increment it, so your condition of 6 will cause the break and then it goes up 1 to 7. I think you're expecting this:

int x = 0;

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

This will increment x before you evaluate its condition.

Nick
  • 645
  • 5
  • 11
1

It is because of the ++

The ++ operator counts x one up everytime it hits the line. And as you have a while(true) loop it will count x one up in the if statement everytime it reaches that if-statement.

RononDex
  • 4,143
  • 22
  • 39
0

Sure, it's 7 because even when it does the check for 6 > 5, it increments by one. Because of the unary operator x++.

Dimitar Dimitrov
  • 14,868
  • 8
  • 51
  • 79
0

x++ increments x after the value has been read. This means that when it increments once after the comparison fails. ++x on the other hand increments before the value is read.

Holstebroe
  • 4,993
  • 4
  • 29
  • 45
  • 1
    This answer is nonsensical; how can a variable be *incremented* before it is *read*? Here, I have a variable x. I'd like you to assign x+1 to that variable, but you're not allowed to read the value of x before you do. How would you do that? – Eric Lippert Jan 07 '14 at 14:39
  • Semantically it makes fine sense to me. The value will not be grammatically read-evaluated before it has been incremented. In machine code, which the code will essentially become, it may indeed be possible to increment a memory location without loading it into a register. – Holstebroe Jan 07 '14 at 19:44