Using Scope
for (i = list.size() - 1; i >= 0; i--)
is more efficient than:
for (int i = 0; i < list.size(); i++)
It is more efficient, but at the cost of being more obscure, easier to misinterpret. One reader suggested using the extended for initialiser:
for (int i = 0, end=list.size(); i < end; i++)
This certainly returns the loop to a more understandable structure, but it is still complex and hence rather difficult to read. All this is because of a fear of cluttering the local scope with variables:
int end = list.size(); for (int i = 0; i < end; i++)
It's not something I'd worried about before now. I guess that is because I started with C where all local variables had to be at the top of the function before the first code. A method should be short enough that variable name confusion should not happen - if it does, your IDE should tell you. If scope concerns you, just place the whole in a scope-limiting block. That is what they are there for, after all:
{
int end = list.size();
for (int i = 0; i < end; i++)
}
On an interesting side note, did you know that i, j, k are still often used as temporary variables for loops because FORTRAN allowed variables starting with i, j or k to be used as integers without being defined?








