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

后端 未结 2 1337
被撕碎了的回忆
被撕碎了的回忆 2021-01-17 19:45

For code,

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

MSVC generates the following warning.

warning C4127: conditional expression is const         


        
2条回答
  •  遇见更好的自我
    2021-01-17 20:32

    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

提交回复
热议问题