Why do you choose for (;;) {}, and (1)?

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

I see it

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

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

+2
source share
4 answers

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

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

  • for (;;) literally reads โ€œJust loop forever!โ€, while while (true) still has some sort of condition.

I say, choose one and stick to it. It doesnโ€™t matter if you do not switch between them arbitrarily.

+5
source

This is the forever loop form that Kernigan and Richie used in their book * . There is absolutely no reason to prefer one form over another.

* Section 3.5 on the While and For loops, example No. 4.

+4
source

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

+3
source

It doesnโ€™t matter - itโ€™s just personal preference.

I like for(;;) better because I think it emphasizes the loop forever.

+2
source

All Articles