I'm new to programming and am in my first year of computer science and am a bit confused about loops. When it comes to infinite loops, why are while and do-while loops preferred over for loops? I created a simple infinite for loop and it's just as easy as creating a while loop. Is one type of loop faster than the other?
Asked
Active
Viewed 839 times
1
-
http://stackoverflow.com/questions/6347862/can-a-for-loop-be-written-to-create-an-infinite-loop-or-is-it-only-while-loops-t – assylias Oct 24 '12 at 22:15
-
BTW, speaking of speed when dealing with infinite loops sounds... weird. ) – raina77ow Oct 24 '12 at 22:15
4 Answers
6
Because it's easier to write (AND read the intention of) while(true)
than for(;;)
, perhaps?

raina77ow
- 103,633
- 15
- 192
- 229
3
A "for()" loop is pretty much equivalent to initializing an index, declaring a while() condition, and incrementing/decrementing the loop.
There is absolutely no performance difference.
"while (true)" is generally preferred over "for (;;)" except for people like me who've read and revere the original K & R "White Book" - "The C Programming Language" :)

paulsm4
- 114,292
- 17
- 138
- 190
2
Neither one is faster than the other. It's just that:
while (true)
{
}
looks more intuitive and human-readable than:
for (; ; )
{
}

user1610015
- 6,561
- 2
- 15
- 18
2
while(true)
is simpler to read than for(;;)
- you don't need to figure out what it means - it's almost spelled out in English.

zmbq
- 38,013
- 14
- 101
- 171