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

这一生的挚爱 提交于 2019-12-10 12:45:49

问题


For code,

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

MSVC generates the following warning.

warning C4127: conditional expression is constant

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?

What flag should I use on GCC to get the same warning?


回答1:


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. 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




回答2:


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."

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.

I don't think GCC has an equivalent warning.



来源:https://stackoverflow.com/questions/3490823/why-msvc-generates-warning-c4127-when-constant-is-used-in-while-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!