Code: Select all
for (int i=0;i<100;i++) {
//do something 100 times (0-99), counting up
}
//or
for (int i=99;i>=0;i--) {
//do something 100 times (99-0), counting down
}
When using these functions, it is common to include them in the for loop expressions, either in the initialization section or the conditional test. For example, to iterate over an array, we could do either
Code: Select all
//initialize array
int A[5]={1,2,3,4,5};
//iterate backwards
for (int i=ArraySize(A)-1;i>=0;i--)
Print(A[i]);
//or
//iterate forwards
for ( i=0; i < ArraySize(A);i++)
Print(A[i]);
The other concern is that sometimes the activity within the loop can change the number of items being iterated over. Deleting objects and closing orders comes to mind. In these cases, it's easy to miss out on evaluating items. Of course, if you are deleting items you should iterate over the list in reverse order anyway (but that's another post).
I recommend capturing the number of items you intend to iterate over into a temporary variable before the iteration. It should be faster and will likely have less troublesome bugs to track down.
Though there may be valid reasons to use a function call within the for loop's conditional expression, personally I think the code would be more readable if you structure the loop as a while loop instead of a for loop.
George
