Wednesday, June 8, 2011

++i vs. i++, YES they are different!

For this first test you will see that there isn't a difference, it is working differently, but you cannot tell the difference in this example:


public static void IncrementTest()
{ 
 Console.WriteLine("\n\n++i");
 for (int i = 0; i < 10; ++i)
 {
  Console.WriteLine(i);
 }

 Console.WriteLine("\n\ni++");
 for (int i = 0; i < 10; i++)
 {  
  Console.WriteLine(i);
 } 
}


This next example highlights the differences between i++ and ++i.


public static void IncrementTest2()
{
 int i = 0;
 
 Console.WriteLine("Initial Value: {0}\n", i);
 
 Console.WriteLine("Param i++ {0}", i++);
 Console.WriteLine("After Param i++ {0}\n", i);

 i = 0;

 Console.WriteLine("Param ++i {0}", ++i);
 Console.WriteLine("After Param ++i {0}\n", i);

 i = 0;
 i++;

 Console.WriteLine("Statement i++ {0}\n", i);

 i = 0;
 ++i;

 Console.WriteLine("Statement ++i {0}\n", i);
}


Conclusion, be careful when writing code, don't assume that things work the same way when written differently.

No comments:

Post a Comment