2

I tried to do the following

i=0;
if (i++ % Max_Col_items == 0 && i !=0)
{

}

and discovered that it increased i in the middle

i % Max_Col_items == 0;
i=i+1;
i !=0;

when I though it would add increase i in the end:

i % Max_Col_items == 0;
i !=0;
i=i+1;

Can any one find explanation of how i++ works in C#?

Nahum
  • 6,959
  • 12
  • 48
  • 69
  • possible duplicate of [What's the difference between X = X++; vs X++;?](http://stackoverflow.com/questions/226002/whats-the-difference-between-x-x-vs-x) – nawfal Jul 20 '14 at 08:09

3 Answers3

3

i++ will give you the original value, not the incremented, You will see the change on the next usage of i. If you want to get the incremented value then use ++i.

See the detailed answer by Eric Lippert on the same issue

Community
  • 1
  • 1
Habib
  • 219,104
  • 29
  • 407
  • 436
  • The OP has made it clear what he expected to happen and what he has observed happening. He doesn't _want_ the incremented value; he wants to know why the value is incremented by the second part of his `&&`. – Rawling Dec 03 '12 at 10:39
  • @Rawling, thats what I said, Change will be visible on the next usage of `i` – Habib Dec 03 '12 at 10:41
  • Eventually, yes. Your original answer just said that `i++` gives the original value and use `++i` if you want the original value, which was irrelevant to the question. – Rawling Dec 03 '12 at 10:43
  • @Rawling, I was in the middle of editing and trying to find the answer by Eric lippert, but thats ok – Habib Dec 03 '12 at 10:45
0

i++ immediately increments the value of i but evaluates as the value before incrementation.

It doesn't leave the value of i untouched until the end of the line of code, which appears to be what you expect.

Rawling
  • 49,248
  • 7
  • 89
  • 127
0

That is because (as you have rightly noted)

i % Max_Col_items == 0;

is an operation in itself. Once that line of operation is over (with value of i ) the increment is done.

Milind Thakkar
  • 980
  • 2
  • 13
  • 20