Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why choosing for (;;){} over while(1)? [duplicate]

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){}?

like image 903
ManuelSchneid3r Avatar asked Mar 31 '26 15:03

ManuelSchneid3r


2 Answers

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.

like image 191
Joseph Mansfield Avatar answered Apr 02 '26 16:04

Joseph Mansfield


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.

like image 39
Sergey Kalinichenko Avatar answered Apr 02 '26 16:04

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!