thanks for the advice, and spaceship

Jeffrey Traer Bernstein jeffyb@ccrma.Stanford.EDU
Tue, 13 May 2003 22:19:44 -0700


You got it backwards again...
++i is faster than i++

++i  is pre-assignment-increment, in other words increment and then 
assign the value
i++ is post-assignment-increment, in other words assign the value then 
increment.

so that means every time you use post-increment a temporary variable 
holding the present state of the variable is created so that it can be 
returned and the actual value incremented, this is the semantic 
definition and how it must be implemented in any class.

as an example:

++i
{
i = i + 1;
return i;
}

and ...

i++
{
int j = i;
i = i + 1;
return j;
}

so....

int i = 0;
cout << i++;

output = 0

and...

int i = 0;
cout << ++i;

output = 1;

this behaviour only comes into play with assignments so since you have 
the pick of the two in loops you should choose the faster one which is 
always ++i. I have no idea why i++ is in every basic loops example in 
every loop. I guess it must have been in a basic example in the 
Kernigan-Ritchie book (the first book on C, by the authors of C, also 
where that "Hello world!" example program now the standard in ALL 
programming text books comes from!)

jeffyb




Hiroko Terasawa wrote:

>Thanks Jeffyb,
>
>  
>
>>use ++i in loops instead of i++, it's pre-increment so it's faster
>>    
>>
>I use i++ for coding, but when writing the mail somehow I was messed up
>(as usual?). But why i++ faster than ++i? Wasn't it about the order of
>increment? Why does it make the code faster?
>
>ps. I found a treat for you...
>http://mirror.wolffelaar.nl/zardalu.sytes.net/
>
>  
>