Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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);
    }

}
}
like image 926
santosh singh Avatar asked Nov 26 '10 18:11

santosh singh


1 Answers

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.

like image 61
SLaks Avatar answered Oct 31 '22 18:10

SLaks