为什么选择 (;;){} 而不是 while(1)?

2021-12-11 00:00:00 loops while-loop for-loop c++

可能的重复:
是for(;;)"比while (TRUE)"快?如果不是,人们为什么要使用它?

我看到了

for (;;)
{
  // Some code here
} 

经常出现.但它提供了什么好处,为什么不选择 while(1){}?

quite often. But what benefits does it offer and why just not choose while(1){}?

推荐答案

它们产生相同的代码.您可能更喜欢 for (;;) 的原因有很多,但这只是个人喜好:

They produce identical code. There are a couple of reasons why you might prefer for (;;) but it is all just personal preference:

  1. 有些编译器会警告您有关始终为真的条件.for(;;) 不会有这个问题.

for (;;) 字面意思是永远循环下去!",而 while (true) 仍然出现有某种条件.

for (;;) literally reads as "Just loop forever!", whereas while (true) still appears to have some kind of condition.

我说选择一个并坚持下去.只要不随意切换都无所谓.

I say pick one and stick with it. It doesn't matter as long as you don't switch between them arbitrarily.

相关文章