-3

Why is the Output of this code gives the value 100. Please help me to understand this behavior.

static void Main(string[] args)  
{  
    int i = 100;  
    for (int n = 0; n < 100; n++)  
    {  
         i = i++;  
    }  
    Console.WriteLine(i);  // This gives the Value 100 why?
}  

I have ran the same code in both C and C# compiler. in C compiler gives the value 200 in C# compiler gives the value 100.

why the same piece of code is behaving like this in two Compilers?

Akshay Joy
  • 1,765
  • 1
  • 14
  • 23

2 Answers2

2

This is the same as

static void Main(string[] args)  
{  
    int i = 100;  
    for (int n = 0; n < 100; n++)  
    {  
       int x = i;
       i++;
       i = x;  
    }  
    Console.WriteLine(i);  // This gives the Value 100 why?
}  

You reassign the 100 all the time in the loop

user1781290
  • 2,674
  • 22
  • 26
0

Because it is post increment. First 100 will be assigned then incremented.

i = i++;

hence the output.

Ehsan
  • 31,833
  • 6
  • 56
  • 65
  • After assign the value is should Increment i right.? why that is not happening.... the same code I have executed in C compiler also. I am getting the value 200. Waht is the difference? – Akshay Joy Jan 02 '14 at 10:34