Reputation: 28692
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);
}
}
}
Upvotes: 6
Views: 8720
Reputation: 532765
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.
Upvotes: 7
Reputation:
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++;
Upvotes: 4
Reputation: 888303
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.
Upvotes: 8
Reputation: 547
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.
Upvotes: 5