why c language needs this for(; ;)
loop ? It is actually an infinite loop and while(1)
also infinite loop. My question is that which one we should use ? I want to know which one is more efficient according to compiler point of view?
Asked
Active
Viewed 162 times
0

anirban karak
- 732
- 7
- 20
-
Both are same & both do the same work- infinite loop. – Jul 17 '13 at 10:53
-
No difference in the effect, I consider `while(1)` clearer. – Antonio Jul 17 '13 at 10:53
-
Generally `while(TRUE)` is more quickly/cleanly understood. – Hot Licks Jul 17 '13 at 10:54
-
exactly the same - personally I prefer `while(1)`, it just looks neater.. – Karoly Horvath Jul 17 '13 at 10:54
-
Legend says it's for historical reasons http://stackoverflow.com/q/8292305/57428 – sharptooth Jul 17 '13 at 10:54
-
FWIW, `do { ... } while(FALSE);` can also be quite useful, to allow you to insert (using `break`) "GOTOs" to the end of the block. Useful for a "filter" that tests some data with multiple sequential validity tests. – Hot Licks Jul 17 '13 at 10:56
-
One point is also that any `for` cycle can be substituted with an equivalent `while` cycle (and initialization), so it's pretty logical that you can find two equivalent ways of doing an infinite cycle. – Antonio Jul 17 '13 at 10:58
-
It's not about need. It's about C allowing empty statements, such as `;;;` or `if (1) { } else { }`. In this particular case C allows any or all of the traditionally used expressions/statements or loop body in `for (statement1;expression1;statement3) body4` to be missing. Also it would be very hard to generate a language where there's always only one way to accomplish some programming task... – Aki Suihkonen Jul 17 '13 at 10:58
3 Answers
3
Both are same. I believe infinite loops are needed when you want to break on a certain condition which the executing code knows only once it enters the loop.
For me this looks more intuitive and easier:
while(1) {}
while(true) {}
Remember even this is an infinite loop :
// just don't provide the condition
for(int i=0; ;i++) // don't mind the syntax as I don't belong to C

AllTooSir
- 48,828
- 16
- 130
- 164
0
For an infinite loop, both do the same thing, but for
and while
are used for different things, and are not generally interchangeable.

SteveLove
- 3,137
- 15
- 17