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:03

Let the flaming begin...

If the loop is a true infinite loop (i.e. there is no break condition -- only an external event can terminate the thread's/process' execution), then I actually prefer the label and goto. Here's why:

First, the use of while, for, and do ... while, all imply that the loop might terminate. Even if the terminating condition is never achievable, the syntactical meaning of these constructs is that there is some termination condition.

Second, using a loop construct introduces an extra level of indentation. I hate indentation that's not necessary. It wastes valuable columnar real-estate.

Third, the only true infinite loop is the one that unconditionally jumps back to the beginning of the loop. Only goto fits that purpose exactly.

The truth is I don't really care that much about it. They all get the job done and most will result in the exact same assembly instructions anyway. However, the assembly that's generated will in all probability be an unconditional jump (if you're optimizer is worth a damn), which maps directly to which C construct, kids? That's right... your old friend goto.

查看更多
不美不萌又怎样
3楼-- · 2019-01-07 23:03

I usually use while() {}, but after learning that for(;;) {} isn't some sort of crazy invalid syntax, I'll be sure to use the more unique option.

Differentiates infinite loops from actual conditionals, you see.

查看更多
劫难
4楼-- · 2019-01-07 23:04

I like to use the for(;;) approach because the MSVC++ compiler complains about while loop approach:

void main()
{
  while(1) // test.cpp(5) : warning C4127: conditional expression is constant
  {
  }

  for(;;)
  {
  }
}
查看更多
我想做一个坏孩纸
5楼-- · 2019-01-07 23:05
while(true) {}

It seems to convey the meaning of the loop most effectively.

查看更多
\"骚年 ilove
6楼-- · 2019-01-07 23:06

for (;;) is what I usually see.

查看更多
爱情/是我丢掉的垃圾
7楼-- · 2019-01-07 23:06

Infinite loops are a bad idea, but in practice that doesn't always hold up.

I prefer while(1) { } but make sure something within the loop can cause it to break out.

查看更多
登录 后发表回答