GP32 Loop Condition


pea

developer
Joined
Oct 3, 2004
Messages
1,089
Age
46
Location
New Zealand
Website
www.projectitis.com
Hi all,

When I do a loop, is the condition evaluated once at the start, or for every iteration? which of these is best:

Code:
for (i=0; i<someFunction(); i++){
  // Do stuff
}
or
Code:
x = someFunction();
for (i=0; i<x; i++){
  // Do stuff
}

Conversly, is it more expensive to reference struct members than a variable directly? Which of these is best:

Code:
a = b[someStruct->member1->member2];
b->x = someStruct->member1->member2;
or
Code:
s=someStruct->member1->member2;
a = b[s];
b->x = s;

Thoughts appreciated!
 
1. The condition evaluated for every iteration :

if the value returned by 'someFunction' does(should) not change during the loop, use this code :

x = someFunction();
for (i=0; i<x; i++){
// Do stuff
}

2. The compiler optimiser will do the work for you. I prefer the second one (1 var more, but less chars to write)

<In your sample, b is an array or a simple pointer to a struct ? you're using it the too ways in the same code...>

my 2 cents,

Thor
 
Thanks for that RTB7. Just noticed that 'b' bug in the sample code :) The second 'b' should be a 'c'
Code:
c->x = someStruct->member1->member2;
 
In the first question, the compiler would sometimes notice that someFunction() is invariant and move it out of the loop. It can only do that if the function is in the same file, and some other conditions are met, so in general it's best to do what rtb7 says.

For the second question: personally, I prefer to make those little optimisations explicit even though the compiler should do them... so again I'm with rtb7, use the extra variable :D
 
Back
Top