i++
and ++i
work differently in a for loop.
Consider the following for loop definition:
for (int i=0; i<1; ++i)
can be written as:
for (int i=0; 1 >= i ; ++i)
This is the equivalent of writing:
for (int i=0; 1 >= ++i; /*No function here that increments i*/)
In this case, the increment is executed before the comparison, and the contents of the loop will never be executed.
Now consider this loop:
for (int i=0; i<1; i++)
can be written as:
for (int i=0; 1 >= i ; i++)
This is the equivalent of writing:
for (int i=0; 1 >= i++; /*No function here that increments i*/)
In this case, the increment is executed after the comparison, and the contents of the loop will be executed once. At the end of the loop, i will have a value of one.
You can test this by doing the following:
int i;
for (i=0; i<1; i++)
{
Console.WriteLine("i in the loop has a value of: " + i);
}
Console.WriteLine("i after the loop has a value of: " + i);
The same rules apply to ternary operators as well.
This case will have the increment execute before assigning the value to k, and k will be 26:
int k=25;
k= (false) ? 0 : ++k
And this case will have increment executed after assigning the value to k, and k will be 25:
int k=25;
k = (false) ? 0 : k++;
k+=1 is not the same as a ++ operator, and k-=1 is not the same as a -- operator.
k+=1 is actually 2 operations written concisely:
k = k+1
It first takes the value of k, adds one to it in memory, then assigns the value back to k.
So in the ternary example:
int k=25;
k = (false) ? 0 : k+=1;
k will be 26. Assignment operators are evaluated from right to left. So the compiler will first evaluate k+=1 - making k 26. Then the ternary comparison will execute, then 26 will be assigned to k.
Summary:
++/-- are special operators and where you put it affects when in the evaluation of an expression it is executed.
++x or --x - the ++ or -- will be evaluated before any comparisons.
x++ or x-- - the ++ or -- will be evaluated after any comparisons