1

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?

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
Cucko Oooo
  • 91
  • 4
  • 14

4 Answers4

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