2

Given the following code

int j = 0;
for (int i = 0; i < str.Length; ++i) {
    if (i==j) {
        Console.WriteLine ("equal");
    }
    j++;
}

I expected that ++i would change i from initial 0 to 1 and thus i==j evaluated to false.

But it did not. Why?

Palec
  • 12,743
  • 8
  • 69
  • 138
TOP KEK
  • 2,593
  • 5
  • 36
  • 62

4 Answers4

13

If you have a loop in the form for (a; b; c) { d; }, you can treat this as the following while loop:

a;
while(b) {
    d;
    c;
}

As you can see, the increment doesn't occur until after the first iteration, regardless of whether it's a pre- or post- increment.

qaphla
  • 4,707
  • 3
  • 20
  • 31
  • is it documented somewhere? – TOP KEK Jun 21 '14 at 12:20
  • @Ask: It is just a trivial consequence of how [`for`](http://msdn.microsoft.com/en-us/library/ch45axte.aspx) is defined and it’s a language-agnostic fact. You can read it e.g. in [*Looping* section of *Chapter 4: Flow Control* in *Beginning Visual C# 2010*](http://msdn.microsoft.com/cs-cz/library/hh147286%28VS.88%29.aspx#Looping). – Palec Dec 20 '14 at 14:03
3

++i (or anything in the 3rd segment) will not be evaluated until after the first iteration.

No matter what though, even if it evaluated before your if, it would still not work the way you thought it did.

Doing i++ or ++i won't change anything because it would have been evaluated prior to it being used.

The true difference comes when you use it like so:

int i = 0;
if (i++ == 0) { /* True because the old value of "i" was used to compare */ }

i = 0;
if (++i == 0) { /* Not true because "i" got changed to 1 before the compare. */ }
TyCobb
  • 8,909
  • 1
  • 33
  • 53
2
  • i++ increments and evaluates to (i.e. results in, similar to returning) i's old value
  • ++i increments and evaluates to i's new value

The statements i++; and ++i; are the same because you don't use the result, so the only important part is that they both increment i. Used in a for loop how you are, you're using them as standalone statements, you aren't using the values of the expressions i++/++i.

Tim S.
  • 55,448
  • 7
  • 96
  • 122
0

The compare is evaluated before the increment. Prefix or postfix makes no difference.

Peter Ritchie
  • 35,463
  • 9
  • 80
  • 98