I have searched the topic and feel I understand ++x vs x++. My problem is that my for loop reacts exactly the same regardless of how I type it.
The following makes absolutely no difference in outcome and I need to know why.
for (int x = 1; x <= 10; ++x)
{
for (int z = 10; z >= x; z--)
{
cout << setw(4) << x << " * " << z << " = " << (x * z)
<< endl;
}
cout << endl;
}
changing to incrementer to "x++" makes no difference. I would expect with ++x to increment x when it enters the loop, vs x++ would increment x after it enters the loop.
Both x++ and ++x increment the value right away. The difference is what they return. x++ returns the old value, whereas ++x returns the new value.
Example:
1 2 3 4 5 6 7 8
int x = 0;
int pre = ++x;
x = 0;
int post = x++;
cout << pre; // outputs '1'
cout << post; // outputs '0'
This only matters when you use ++ in a compound operation. For example in the above, I'm incrementing and assigning in the same statement, therefore which you use makes a difference. However if the increment is in its own operation (which is the case when you use it in a for loop like your example), it doesn't really matter.
Obligatory suggestion: get in the habit of using ++x instead of x++. For basic types like int it doesn't matter which you use, but for complex types (like iterators, or other classes) it might increase performance because it doesn't require a copy.
> it might increase performance because it doesn't require a copy.
A good compiler should optimize x++ to ++x where it matters (and doesn't change the semantics, of course). Still, I always use ++x unless x++ is required.
It's not always possible to optimize that away. If, for example, the implementation for x++ isn't inlined. Even then -- you might not be able to optimize away a copy because it might break other rules (copy ctor may change a static/global variable, for instance -- in which case optimizing away the copy would result in incorrectly compiled code).
But yeah -- there might be instances where ++x might have a performance increase. And in those cases the performance increase is going to be quite small, if anything. My point was that using ++x never hurts, and sometimes helps. So getting in the habit of preferring it is win/win.
A for loop declaration line can be expanded like so:
for ( int i = 0; i < 10; ++i ) {
...
}
Is identical to:
{
int i = 0;
while ( i < 10 ) {
...
i++;
}
}
In this form it's quite clear how prefix and postfix acts the same.
Disch: I was imagining it would be a simple, obvious optimization. But I see that you're right, it can get complicated. Code optimization must be a fascinating, complex field.