I am trying to show by example that the prefix increment is more efficient than the postfix increment.
In theory this makes sense: i++ needs to be able to return the unincremented original value and therefore store it, whereas ++i can return the incremented value without storing the previous value.
But is there a good example to show this in practice?
I tried the following code:
int array[100];
int main()
{
for(int i = 0; i < sizeof(array)/sizeof(*array); i++)
array[i] = 1;
}
I compiled it using gcc 4.4.0 like this:
gcc -Wa,-adhls -O0 myfile.cpp
I did this again, with the postfix increment changed to a prefix increment:
for(int i = 0; i < sizeof(array)/sizeof(*array); ++i)
The result is identical assembly code in both cases.
This was somewhat unexpected. It seemed like that by turning off optimizations (with -O0) I should see a difference to show the concept. What am I missing? Is there a better example to show this?
array
stores in its elements, you are likely to end up with a bug if you usesizeof(int)
instead ofsizeof(*array)
since the chance is big that you will forget to also change on that place. Code is constantly changing, thus always aim to make it as easy as possible to make changes to it, which usually means reducing the number of places you have to change in the code in order for a change to take place, especially if those are places that will compile even if you don't change them (like in this case). – Sherillsherilyn