开发者

Should I use `while (true)` or `for (;;)` (in languages that support both)? [duplicate]

This question already has answers here: Closed 12 years ago.

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:

  1. Whatever your current code style guide says
  2. Whatever is in use in the current code
  3. Whatever your manager prefers
  4. Whatever your co-workers prefer
  5. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜