Should I use `while (true)` or `for (;;)` (in languages that support both)? [duplicate]
Possible Duplicate:
When implementing an inf开发者_如何学Goinite loop, is there a difference in using while(1) vs for(;;) vs goto (in C)?
In languages where while (true)
or for (;;)
both mean "loop forever", which should I use?
In my opinion, while(true)
is clearer.
Any half-decent compiler will compile both identically (at least with optimizations).
Therefore, you should choose whichever form you find clearer.
for(;;)
has no obvious semantic value. Whereas
while(true)
could pretty much be understood by any reasonably intelligent non-programmer due to being far closer to the natural-language equivalent.
In order of importance:
- Whatever your current code style guide says
- Whatever is in use in the current code
- Whatever your manager prefers
- Whatever your co-workers prefer
- Whatever you prefer
Order of 3 and 4 could be reversed in some circumstances ;)
EDIT: I personally prefer "while (true)" (including space), but I seldomly arrive at point 5 in the list.
I prefer
do {
// ....
} while(true);
It demotes the implementation choice for the infinite loop concept from the prominent place of the start of the loop.
If this is C++ or C, just create your own macro to abstract the concept better (in this case, the use of while(TRUE)
or for(;;)
is not that relevant):
#define forever for(;;)
This can be somehow adapted to C# too:
forever: {
// ...
goto forever;
}
(goto
is not evil in this case)
I prefer while(true) because I think it is more intuitive, elegant and philosophically interesting.
However it is ultimately just a matter of style.
any decent developer will pass over both without getting confused. use whatever you feel like.
A question I asked recently: Difference between for(;;) and while (true) in C#?
Although mine was language specific, several of them expressed views on this very subject.
Personally, I prefer while (true)
because I feel like for (;;)
is leaving out almost necessary pieces. I'm a bit OCD about it, and I know they're not NECESSARY, but I feel that a for
without parameters just looks incomplete. Obviously, there are situations where you don't want some of the parameters, but while (true)
looks more syntactically complete to me in situations where a loop like this is warranted.
All in all, it's pretty moot (in a good way). Developers you work with should be able to understand that they're the same thing, and (at least in C# according to my question) they compile to the exact same thing. Anybody that complains because you did one instead of the other seems like they have their priorities a touch out of order.
精彩评论