简体   繁体   English

当“while” - C中使用常量时,为什么MSVC会生成警告C4127

[英]Why MSVC generates warning C4127 when constant is used in “while” - C

For code, 对于代码,

while(1)
{
   /* ..... */
}

MSVC generates the following warning. MSVC生成以下警告。

warning C4127: conditional expression is constant

MSDN page for the warning suggests to use for(;;) instead of while(1) . 警告的MSDN页面建议for(;;)而不是while(1) I am wondering what advantage for(;;) is giving and why it warns for the constant usage in while ? 我想知道for(;;)有什么好处for(;;)以及为什么它会在while不断使用?

What flag should I use on GCC to get the same warning? 我应该在GCC上使用什么标志来获得相同的警告?

Constant conditionals are often enough simply bugs. 恒定条件通常就足够了。 Consider this: 考虑一下:

unsigned k; 
...
while (k>=0) 
{
 ...
}

The condition k>=0 would make sense if k was a signed int, but not for unsigned. 如果k是带符号的int,则条件k>=0是有意义的,但对于无符号则不是。 A careless developer forgets that k was declared unsigned and he/she would use it as if it was usable as a negative number. 粗心的开发人员忘记了k被声明为无符号,并且他/她会使用它,好像它可用作负数。 The compiler tries to be helpful and warn you about this and while(1) falls for the compiler into the same problem class. 编译器会尝试提供帮助并向您发出警告, while(1)编译器会陷入同一个问题类。 for(;;) is preferable because it unambiguously means `loop forever for(;;)是优选的,因为它明确地表示`循环循环

for(;;) and while (true) are different in that the former is a special case defined to be an infinite loop, while the latter is sort of an abuse saying "true, always." for(;;)while (true)的不同之处在于前者是一个被定义为无限循环的特殊情况,而后者则是一种滥用说“真实,永远”。

The warning comes up because infinite loops when you don't want them are pretty bad, so it's warning you that you might have one at the first sign. 警告出现是因为当你不想要它们时,无限循环是非常糟糕的,所以它警告你,你可能在第一个标志处有一个。 But by using for(;;) , you've pretty much explicitly said "loop this forever", and there's nothing to warn about. 但是通过使用for(;;) ,你几乎明确地说“永远地循环”,没有什么值得警告的。

I don't think GCC has an equivalent warning. 我不认为海湾合作委员会有同等的警告。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM