6

I have a simple c# console application but i am getting wrong output why?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication11
{
class Program
{
    static void Main(string[] args)
    {
        int i = 100;
        for (int n = 0; n < 100; n++)
        {
            i = i++;
        }
        Console.WriteLine(i);
    }

}
}
Fredou
  • 19,848
  • 10
  • 58
  • 113
santosh singh
  • 27,666
  • 26
  • 83
  • 129
  • Old question about the same construction in Java: http://stackoverflow.com/questions/3831341/why-does-this-go-into-an-infinite-loop – Rup Nov 26 '10 at 18:56
  • possible duplicate of [Post-increment Operator Overloading](http://stackoverflow.com/questions/668763/post-increment-operator-overloading) – nawfal Jul 20 '14 at 07:18

5 Answers5

8

i++ is an expression which returns i, then increments it.

Therefore, i = i++ will evaluate i, increment i, then assign i to the original value, before it was incremented.

You need to use ++i, which will return the incremented value.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
7

I'm guessing that you really want an explanation as to why it doesn't work as expected, rather than to actually get the result since you can get that by setting i equal to 200 in the first place.

The postincrement operator is applied after a temporary copy of the variable is created. The temporary is used for operations in the statement then the assignment is performed, thus your loop is equivalent to:

    for (int n = 0; n < 100; n++)
    {
        j = i;
        i++;
        i = j;
    }

Since that's the case, the increment is basically discarded and i is never actually incremented.

tvanfosson
  • 524,688
  • 99
  • 697
  • 795
5
i = i++;

This sets i to the old value of i, then increments it. I think you want:

i++;

Or better yet if your compiler is lame and doesn't optimize the return:

++i;

Cheers.

Hank
  • 547
  • 3
  • 4
4

The line i = i++; writes twice to the variable i. The post increment is executed first, but then the assignment statement overwrites it.

Try just i++;

3

Just use i++, not i = i++.

Jimmy Collins
  • 3,294
  • 5
  • 39
  • 57