2

Possible Duplicate:
Is “for(;;)” faster than “while (TRUE)”? If not, why do people use it?

I see this

for (;;)
{
  // Some code here
} 

quite often. But what benefits does it offer and why just not choose while(1){}?

Community
  • 1
  • 1
ManuelSchneid3r
  • 15,850
  • 12
  • 65
  • 103

4 Answers4

5

They produce identical code. There are a couple of reasons why you might prefer for (;;) but it is all just personal preference:

  1. Some compilers will warn you about conditions that are always true. for(;;) will not have that problem.

  2. for (;;) literally reads as "Just loop forever!", whereas while (true) still appears to have some kind of condition.

I say pick one and stick with it. It doesn't matter as long as you don't switch between them arbitrarily.

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
  • 1
    Personal opinion, but `for (;;)` literally reads as bad form to me, while `while(true)` literally reads as "Just loop forever!" They are completely identical in behavior and in assembly code produced by the compiler. – David Hammen Nov 24 '12 at 21:36
  • @DavidHammen Precisely! I was just giving a reason why `for (;;)` might be more common. – Joseph Mansfield Nov 24 '12 at 21:40
4

This is the form of the forever loop that Kernighan and Ritchie used in their book*. There is absolutely no other reason to prefer one form over the other.

* Section 3.5 on While and For loops, example number four.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • It's 1 character smaller. And [Go](http://golang.org/doc/effective_go.html#for) doesn't even have a while loop, so it's easier for Go programmers to understand? – beatgammit Nov 24 '12 at 20:29
3

The two are equivalent and will most likely result in identical machine code. Choosing one over the other is a matter of personal preference.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
2

It does not really matter - it is just personal preference.

I like for(;;) better because I think it underlines loop forever aspect.

mvp
  • 111,019
  • 13
  • 122
  • 148