ive been looking around the forums and i havent seen this one yet.
is a for loop better to use then a while loop?
are there situations when you would want to use one over the other?
or is it all syntax?
thanks in advance.
~M.I.
Printable View
ive been looking around the forums and i havent seen this one yet.
is a for loop better to use then a while loop?
are there situations when you would want to use one over the other?
or is it all syntax?
thanks in advance.
~M.I.
Really? I thought it had been done to death.
Yes. No. Use whichever fits the loop best. That is, if you are going from here to there, a for loop seems quite well suited for the task. If you are looping until some condition is met, a while loop may be better suited.
Preference to a degree. I'd say it mostly has to do with whether your loop needs an initial condition and/or specific "increment" or not.
cool, thanks for the insight!
Now you're gonna ask yourself, when should I use:
and when should I use:Code:while ( condition )
{
...
}
;)Code:do
{
...
} while ( condition )
It used to be that for-loops where slightly better optimized (this is about 15 years ago, when compilers had to live in DOS where 640K was the limit, and non-PC machines has a few MB of RAM to share between different apps & users). In such a system, the compiler will not be able to do advanced optimizations that require building multiple large code-paths and check which is faster/better/shorter (whichever applies) - or if it did, it would make the compiler seriously slow, and whilst optimization is nice, having a compile that finishes the same day you started it is also useful.
Nowadays, using a modern compiler, if you do the same work, you most likely end up with the same code, as long as you go about it in a reasonably similar way.
Some "interesting" uses of for & while:
--Code:for(;;) ... // same as while(1)
for(p = head; p; p = p->next) ... // Walk through a linked list from head to tail.
// Same code using while...
p = head;
while(p) {
...
p = p->next;
}
for(i = 0; i < 10; i++) ...
// Same code using while using ugly coding style
i = -1;
while(i++, i < 10) ...
// Alternatively:
i = 0;
while(i < 10) {
...
i++;
}
Mats
thanks guys, i really appreciate the help.