for(;true;) different from while(true)?

2020-08-17 04:57发布

问题:

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 (;;).

回答1:

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).



回答2:

Yes, it is just taste.



回答3:

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.



回答4:

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.



回答5:

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.



回答6:

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.



回答7:

An optimizing compiler should generate the same assembly for both of them -- an infinite loop.



回答8:

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.



标签: c++ c