beware of loop invarinats

This tip submitted by Iain on 2005-02-27 14:43:27. It has been viewed 41620 times.
Rating of 5.8 with 197 votes

Be aware of loop invariants and how they can affect code efficiency . An example:

If you have code within a loop tha uses non-varying variables:

for(i = 0; i < 100; i++)
total = i + x + y;
printf(\"%d\", total);
} //end for

as you can see, x and y are not variable within the loop and so it is much more efficient to code the loop as follows:

total = x + y;
for (i = 0; i < 100; i++)
total += i;

this is because the loop does one less addition on each loop cycle.

More tips

Help your fellow programmers! Add a tip!