4 ms·
Why do people write while(1) instead of for(;;)? Are you saying that "while(1)" is superior in some way? Why? I prefer "for(;;)" because it is explicitly defin
by pslam 14y ago
Why do people write while(1) instead of for(;;)? Are you saying that "while(1)" is superior in some way? Why?
I prefer "for(;;)" because it is explicitly defined as an infinite loop, but "while(1)" needs an implicit cast of "1" to "true", and even then there's an implicit test for "true".
- sp332 14y agoYou could just say while(true). And I'm not sure that the test for true is implicit, since that is what while() explicitly does.
- zanny 14y agoC doesn't have true / false as language constants, only as override-able macros. The good thing is modern compilers can evaluate a loop and if the break condition is constant it can just do an infinite loop without checking.
- barbs 14y agoI guess it's just personal preference. "for(;;)" looks really messy to me, and doesn't seem obvious that it signifies an infinite loop. I think that even the standard format for for loops (for (initialisation; condition; thing done at end of loop)) is quite unintuitive, and I have to think a bit to remember what each part does if one of them is omitted. It's also the only place I can think of where semicolons aren't expected at the end of a line (conventionally). I don't find a problem implicitly casting "1" to "true", I sort of do this automatically after programming in C for a while. Obviously if I were using java or something, I'd use "while(true)". Basically, I don't have to think much to know that it's an infinite loop :)
- wollw 14y agoTrue and false are actually defined as 1 and 0 respectively. I don't have a copy of the standard but this specifies true and false as macros. http://pubs.opengroup.org/onlinepubs/007904975/basedefs/stdbool.h.html http://pubs.opengroup.org/onlinepubs/007904975/basedefs/stdb... Edit: Of course I'm talking about C here. Also, I prefer for(;;) because it's an easy to recognize idiom that means "infinite loop."
- tsahyt 14y agoThere's no casting involved in while(1). 1 is "true" in C, in fact, any integer != 0 is "true". I just did a quick check and gcc -S produces the same ASM output for both of them, which doesn't include any comparisons whatsoever, just a jmp. So both of them are really compiled to an actual infinite loop.