Hahaha, wow, I messed that up, good job figuring out my own mistake and what I was trying to get across to you.
++variable_name is pre-increment
variable_name++ is post-increment
Difference between the two:
Code: Select all
int increment( int value )
{
value += 1;
return value;
};
int i = 0;
// Preincrement
i = increment( i );
// ... use i ( now i is 1 )
// Post increment
int j = i;
i = increment( i );
// ... use j ( j == 1 and i == 2 )
Here is equivalent code using an increment function in a while loop to simulate pre-increment
Code: Select all
int i = 0;
Enemy enemies[10];
while( i < 10 )
{
enemies[ i ].SetPositionX( 200 );
enemies[ i ].SetPositionY( 100 );
// value of i = 0
i = increment( i );
}
Here is the same loop, but simulating post increment
Code: Select all
int i = 0;
Enemy enemies[10];
while( i < 10 )
{
enemies[ i ].SetPositionX( 200 );
enemies[ i ].SetPositionY( 100 );
int j = i;
i = increment( i );
}
Hopefully, you can see that post-increment has an added step. Even though the result is the same in the loop ( because it's the last instruction ), the preincrement operator is slightly ( very slightly ) more efficient. While it doesn't play a huge role here with integers, there are some uses for each.
Let's say you wanted to get the value of something at index 'i' and needed to increment 'i' afterward.
Code: Select all
int pos_x = enemy[ i ].GetPositionX();
i += 1;
You could just increment i in the [ ] brackets using the post increment version
Code: Select all
int pos_x = enemy[ i++ ].GetPositionX();
Here's a use for pre-increment that I've used before. I didn't want to count each element,
so I just increment i as I go.
Code: Select all
int i = -1;
Enemy enemies[] = {
Position{ 400 + ( 10 * ++i ), 300 + ( 5 * i ) }, // i = 0 ( x = 400 + 0, y = 300 + 0 )
Position{ 400 + ( 10 * ++i ), 300 + ( 5 * i ) }, // i = 1 ( x = 400 + 10, y = 300 + 5 )
Position{ 400 + ( 10 * ++i ), 300 + ( 5 * i ) }, // i = 2 ( x = 400 + 20, y = 300 + 10 )
Position{ 400 + ( 10 * ++i ), 300 + ( 5 * i ) }, // i = 3 ( x = 400 + 30, y = 300 + 15 )
Position{ 400 + ( 10 * ++i ), 300 + ( 5 * i ) }, // i = 4 ( x = 400 + 40, y = 300 + 20 )
Position{ 400 + ( 10 * ++i ), 300 + ( 5 * i ) }, // i = 5 ( x = 400 + 50, y = 300 + 25 )
Position{ 400 + ( 10 * ++i ), 300 + ( 5 * i ) }, // i = 6 ( x = 400 + 60, y = 300 + 30 )
Position{ 400 + ( 10 * ++i ), 300 + ( 5 * i ) }, // i = 7 ( x = 400 + 70, y = 300 + 35 )
Position{ 400 + ( 10 * ++i ), 300 + ( 5 * i ) }, // i = 8 ( x = 400 + 80, y = 300 + 40 )
Position{ 400 + ( 10 * ++i ), 300 + ( 5 * i ) } // i = 9 ( x = 400 + 90, y = 300 + 45 )
};
// value of i after setting enemy[9] position is 10
If you think paging some data from disk into RAM is slow, try paging it into a simian cerebrum over a pair of optical nerves. - gameprogrammingpatterns.com