为什么MSVC产生恒定时使用警告C4127"而" - C [英] Why MSVC generates warning C4127 when constant is used in "while" - C
问题描述
有关code,
while(1)
{
/* ..... */
}
MSVC生成下列警告。
MSVC generates the following warning.
warning C4127: conditional expression is constant
MSDN ,在警告页面提示使用为(;;)
而不是,而(1)
。我想知道有什么优势为(;;)
所赐,为什么它警告说,在的不断使用,同时
?
MSDN page for the warning suggests to use for(;;)
instead of while(1)
. I am wondering what advantage for(;;)
is giving and why it warns for the constant usage in while
?
我应该使用GCC上什么标志得到同样的警告?
What flag should I use on GCC to get the same warning?
推荐答案
恒条件等都很往往不够简单的错误。试想一下:
Constant conditionals are often enough simply bugs. Consider this:
unsigned k;
...
while (k>=0)
{
...
}
状况 K> = 0
才有意义,如果K是一个符号整数,而不是符号。一个不小心忘记了开发商当k被宣布无符号和他/她会使用它,如果它能够作为一个负数。编译器将尝试是有益的,提醒你这件事,而(1)
落在编译器同样的问题类。 为(;;)
是preferable,因为它明确地意味着永远`循环
The condition k>=0
would make sense if k was a signed int, but not for unsigned. A careless developer forgets that k was declared unsigned and he/she would use it as if it was usable as a negative number. The compiler tries to be helpful and warn you about this and while(1)
falls for the compiler into the same problem class. for(;;)
is preferable because it unambiguously means `loop forever
这篇关于为什么MSVC产生恒定时使用警告C4127"而" - C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!