Thread: i++ and ++i
View Single Post
Join Date: Jun 2004
Posts: 436
Reputation: Chainsaw is an unknown quantity at this point 
Solved Threads: 10
Chainsaw's Avatar
Chainsaw Chainsaw is offline Offline
Unprevaricator

Re: i++ and ++i

 
0
  #3
Aug 14th, 2004
You asked about loops and if's. Here's some:

LOOPS
for (int i = 0; i < 10; i++)
- vs -
for (int i = 0; i < 10; ++i)

no effective difference.

for (int i = 0; ++i < 10; )
- vs -
for (int i = 0; i++ < 10; )

Here, the first one will loop 9 times (1..9), the second one 10 (0..9). In both, the value of i in the body of the loop will be 1-based rather than 0 based.

IF/WHILE
if (i++ < 10)
while (i++ < 10)
- vs -
if (++i < 10)
while (++i < 10)

The second set will execute one less than the first set, same as the for ().

This is 'undefined' and tends to work differently on different compilers, and differently between optimized and non-optimized builds:

int i = j++ + j++;
int i = ++j + j++;

and the like. And though this might sound silly, consider this:

  1. #define MAX(x,y) ((x > y) ? x : y)
  2.  
  3. int i = 10;
  4. int j = 11;
  5. int k = MAX(i,++j); // j gets incremented multiple times!

That's a big advantage of small inlined functions vs #defines; the lack of those side effects:

  1. inline int MAX(int x, int y) { return ((x > y) ? x : y); }
  2.  
  3. int i = 10;
  4. int j = 11;
  5. int k = MAX(i++,j); // k will be 11
Reply With Quote