Is For (; true;) different from while (true)?

If my understanding is correct, they do the same. Why would anyone use the for option? Does it just taste?

Edit: I suppose I also thought about (;;).

+10
c ++ c
Jan 13 '09 at 20:39
source share
8 answers
for (;;) 

often used to prevent compiler warnings:

 while(1) 

or

 while(true) 

usually generates a compiler warning about a conditional expression that is constant (at least at the highest warning level).

+40
Jan 13 '09 at 20:43
source share

Yes, it just tastes.

+8
Jan 13 '09 at 20:40
source share

I have never seen for (;true;) . I saw for (;;) , and the only difference seems to be one of the tastes. I found that C programmers prefer for (;;) bit over while (1) , but this is still just a preference.

+6
Jan 13 '09 at 20:41
source share

Not an answer, but a note: sometimes recalling that for (; x;) is identical to while (x) (in other words, just saying β€œwhile” when I look at the central expression of the conditional expression if) helps me analyze unpleasant statements. ..
For example, it becomes obvious that the central expression is always evaluated at the beginning of the first pass of the loop, something that you can forget, but definitely when you look at it in the while () format.

It’s also sometimes useful to remember that

 a; while(b) { ... c; } 

almost (see comments) just like

 for(a;b;c) { ... } 

I know this is obvious, but an active awareness of these relationships really helps to quickly transform one form and another in order to clarify the confusing code.

+4
Jan 13 '09 at 22:06
source share

Some compilers (with warnings turned off completely) will complain that while(true) is a conditional statement that can never fail, while they are happy with for (;;) .

For this reason, I prefer to use for (;;) as the idiom of an infinite loop, but I don't think this is a big deal.

+3
Jan 13 '09 at 20:43
source share

This is the case if they plan to use the real for () loop later. If you see (; true;), the code is probably for debugging.

+1
Jan 13 '09 at 20:42
source share

The optimizing compiler must generate the same assembly for both of them - an infinite loop.

0
Jan 13 '09 at 22:57
source share

The compiler warning has already been discussed, so I approach it from the point of view of semantics. I use while (TRUE), not for (;;), because, in my opinion, while (TRUE) sounds like it makes more sense than ((;;). I read while (TRUE) as "while TRUE is always TRUE." Personally, this improves code readability.

So, Zeus forbids me from documenting my code (it happens -NEVER-, of course), it remains a little more readable than the alternative.

But, in general, this is the same picky thing that comes to personal preferences in 99% of cases.

0
Jan 14 '09 at 13:53
source share



All Articles