As you know, for loops are a coding shortcut a while loop that uses an incrementing counter.
many while loops are structure like so:
code:
<setup>
while (<condition>)
{
<increment>
}
// for example:
i = 0;
while (i < 10)
{
i++; // same as i = i + 1
}
These tend to work well as for loops.
code:
for (<setup>; <condition>; <increment>)
{
}
// for example:
for (i = 0; i < 10; i++)
{
}
However, there are other cases, where a while loop is sufficient. Especially, if you don't need the setup or increment steps.
For example:
code:
while( functionIsTrue() )
{
}
such as
code:
while( ! frozenOver(hell) )
{
}
I tend to use a for loop only if the setup, condition and increment are all simple and involve the same variable. Otherwise, the code is probably easier to read in a while loop.
If there is a difference in performance, it is quite small and not worth worrying about. Trying to speed up your code? Changes in design and algorithms will give you big gains. Little changes in coding style only give you little gains.




Reply With Quote