If my understanding is correct, they do exactly the same thing. Why would anyone use for the "for" variant? Is it just taste?
Edit: I suppose I was also thinking of for (;;).
If my understanding is correct, they do exactly the same thing. Why would anyone use for the "for" variant? Is it just taste?
Edit: I suppose I was also thinking of for (;;).
I've never seen for (;true;)
. I have seen for (;;)
, and the only difference seems to be one of taste. I've found that C programmers slightly prefer for (;;)
over while (1)
, but it's still just preference.
It's in case they plan to use a real for() loop later. If you see for(;true;), it's probably code meant to be debugged.
Some compilers (with warnings turned all the way up) will complain that while(true)
is a conditional statement that can never fail, whereas they are happy with for (;;)
.
For this reason I prefer the use of for (;;)
as the infinite loop idiom, but don't think it is a big deal.
for (;;)
is often used to prevent a compiler warning:
while(1)
or
while(true)
usually throws a compiler warning about a conditional expression being constant (at least at the highest warning level).
Not an answer but a note: Sometimes remembering that for(;x;) is identical to while(x) (In other words, just saying "while" as I examine the center expression of an if conditional) helps me analyze nasty for statements...
For instance, it makes it obvious that the center expression is always evaluated at the beginning of the first pass of the loop, something you may forget, but is completely unambiguous when you look at it in the while() format.
Sometimes it also comes in handy to remember that
a;
while(b) {
...
c;
}
is almost (see comments) the same as
for(a;b;c) {
...
}
I know it's obvious, but being actively aware of this relationship really helps you to quickly convert between one form and the other to clarify confusing code.
An optimizing compiler should generate the same assembly for both of them -- an infinite loop.
The compiler warning has already been discussed, so I'll approach it from a semantics stand-point. I use while(TRUE) rather than for(;;) because in my mind, while(TRUE) sounds like it makes more sense than for(;;). I read while(TRUE) as "while TRUE is always TRUE". Personally, this is an improvement in the readability of code.
So, Zeus forbid I don't document my code (this -NEVER- happens, of course) it stays just a little bit more readable than the alternative.
But, overall, this is such a nit-picky thing that it comes down to personal preference 99% of the time.