5 ms·
Why is for(;;) used instead of while(true)? I've seen this idiom used many times but never understood the reasoning why. According to this[0] SO, there are no p
by _asummers 12y ago
Why is for(;;) used instead of while(true)? I've seen this idiom used many times but never understood the reasoning why. According to this[0] SO, there are no performance gains, so why would one prefer the for version?
[0] http://stackoverflow.com/questions/2288856/when-implementing-an-infinite-loop-is-there-a-difference-in-using-while1-vs-f http://stackoverflow.com/questions/2288856/when-implementing...
- LeonRobrotsky 12y ago7 vs 11 characters and I'm lazy.
- corysama 12y agoThey are equivalent. It's just a matter of personal preference. I like it because it's shorter and it doesn't read as a loop that evaluates the value 'true' on each iteration. Even though you know the evaluation optimizes away trivially if you think about it, I don't even want to think that far when I'm scanning code.
- nchelluri 12y agoI had a professor who gave some reasoning about this. He's written a paper: http://plg.uwaterloo.ca/~pabuhr/papers/MELoop.ps http://plg.uwaterloo.ca/~pabuhr/papers/MELoop.ps I haven't read the whole thing but I like this bit: > There are many algorithms that are best written using an exit from the middle of a loop. If not written in this fashion, techniques such as the traditional “priming” of a loop must be used. For example, in reading a file: read(a, b, c) WHILE NOT eof DO { process a, b, & c } read(a, b, c) END WHILE LOOP read(a, b, c) WHEN eof EXIT { process a, b, & c } END LOOP > The example on the left [top] shows the priming of a loop. This requires duplication of the READ statement or, in other cases, creation of a subprogram to eliminate the duplication, both of which are undesirable. As well, loop priming can be done an arbitrary distance before the beginning of the loop making the program difficult to read as the priming statement(s) is critical to the understanding of the loop.
- ternaryoperator 12y agoIn the first versions of C, 'true' was not a keyword, so for(;;) was the way an endless loop was encoded. After that, it became the convention.
- pcthrowaway 12y agoI just started learning Go last night, but I'll hazard a guess: since Go draws heavily from C, but has the for loop as its only looping construct, it seems likely that this habit has carried back into C code written by developers who've used Go, or who've been reading a lot C code written by developers who also use Go.
- jsprogrammer 12y agofor(;;) existed way before Go came along.
- pcthrowaway 12y agoI'm not saying it didn't, but 'while (true)' would be the more intuitive way to write that in any language besides Go.
- throwawayfor 12y agoAnother reason is that MSVC whines about loop conditionals evaluating to constants. Or at least it used to. So while(1) would cause a warning, but not for(;;)