Infinite loops - top or bottom? [closed]

2019-01-07 23:02发布

In the spirit of questions like Do your loops test at the top or bottom?:

Which style do you use for an infinite loop, and why?

  • while (true) { }
  • do { } while (true);
  • for (;;) { }
  • label: ... goto label;

19条回答
甜甜的少女心
2楼-- · 2019-01-07 23:07

I usually use for(;;) { } which I always think of as "for-ever".

Some languages offer a repeat { } construct which will natively loop forever. I find the for(;;) { } construct visually the most similar to this because it is so different from the normal for() construct. This is an important attribute for an infinite loop that while(1) { } doesn't really have.

查看更多
戒情不戒烟
3楼-- · 2019-01-07 23:09

I now prefer the "for (;;)" idiom because it seems to 'stick out' more. I used to use the "while (true)" idiom because I thought it expressed intent better, but I've switched over because I think the "for (;;)" idiom is well known enough to adequately express intent as well as I believe it's better by being more visible.

Kind of like how Stroustrup made the new casts in C++ purposefully ugly - so they stick out.

查看更多
萌系小妹纸
4楼-- · 2019-01-07 23:11

offtopic: if you think about what you are trying to express, you usually won't need an infinite loop.

查看更多
Juvenile、少年°
5楼-- · 2019-01-07 23:12

Infinite tail-recursion ;)

It's somewhat compiler-dependant...

查看更多
一纸荒年 Trace。
6楼-- · 2019-01-07 23:16

PLEASE DO COME FROM (23)

查看更多
狗以群分
7楼-- · 2019-01-07 23:18
10 some l33t code
20 goto 10
查看更多
登录 后发表回答