santosh singh
santosh singh

Reputation: 28692

C# Increment operator (++) question:Why am i getting wrong output?

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

Answers (5)

tvanfosson
tvanfosson

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

Jimmy Collins
Jimmy Collins

Reputation: 3304

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

Upvotes: 3

user180326
user180326

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

SLaks
SLaks

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

Hank
Hank

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

Related Questions