Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the point of issuing a compiler warning for "while(true)" and not issuing one for "for(;;)"?

When I compile C++ code with Visual C++ 9 with "warning level 4" the following:

while( true ) {
   //loop body with break on certain condition
}

and the following:

for( ; true; ) {
   //same loop body
}

both trigger C4127: conditional expression is constant warning but the following:

for( ; ; ) {
   //same loop body
}

compiles without warning.

Why this difference, especially between the second and the third variant?

like image 439
sharptooth Avatar asked Mar 10 '11 10:03

sharptooth


2 Answers

The reason for warning the user of constant conditional expressions is to help avoid bugs where the expression ends up being constant (for example, due to a typo). In the last case, there is no expression, so there is no risk of it accidentally being constant.

like image 52
Tal Pressman Avatar answered Sep 28 '22 07:09

Tal Pressman


The reason is simple, though stupid.

It is important to diagnose infinite loop, but such might not be evident:

while(i >= 0) { --i; } // infinite if i unsigned

while(SOME_MACRO(i)) // err, depends on the expansion of macros

It is a great feature of a compiler to produce a warning for a tautological test, that is a test that turns out to be either always true or always false, because it's not obvious when it comes from a macro expansion or within a dependent context.

It just seems that VC++ pushed a bit too far here, and instead of considering tautological conditions warns for all true or false conditions it can find, even when they are already clearly stated in the code.

like image 30
Matthieu M. Avatar answered Sep 28 '22 06:09

Matthieu M.