C4127 Warning Message May Be Generated with Loop Optimization

ID Number: Q67356

6.00 6.00a | 6.00 6.00a

MS-DOS | OS/2

Summary:

Under certain circumstances, a C4127: "conditional expression is

constant" warning may be generated by the compiler when loop

optimization (/Ol) is enabled. The warning message usually involves a

comparison of unsigned numbers, where an unsigned is being checked

against zero because an unsigned value must ALWAYS be greater than or

equal to zero. However, this warning can also occur with loop

optimization; in that case, it is an indication that the loop will be

executed at least once.

More Information:

When you specify /Ol optimization, the compiler normally places two

tests in the code: one at the beginning of the loop and one at the

end. Consider the following sample program:

unsigned foo (unsigned x, unsigned y)

{

unsigned i;

for ( i = 0 ; i <= x ; i++ )

y += i;

return y;

}

Without loop optimization, the compiler does generate code that

includes a test before the loop to check the initial condition, and

then a check at the end to see if the loop should be terminated.

In this case, however, the variable i starts out as zero and the

initial test checks whether i is less than or equal to x, which must

be true because x is unsigned. This given condition allows the

compiler to optimize the loop by removing the initial test because the

possible values for i and x guarantee that the loop will always be

executed at least once.

When the compiler optimizes out the first test based on this fact, it

generates the C4127 warning message to inform you of the situation.

This message does not necessarily indicate any problems, it just lets

you know that loop will be executed at least once no matter what the

value of i is. This would be important if you expect a value of zero

to cause the loop to not be executed.

If loop optimization is disabled or signed numbers are used instead of

unsigned, then the warning will not be generated. Also, changing the

comparison from "<=" to just "<" will prevent the compiler from being

able to assume that the comparison will always be true the first time

around.

Since the warning message itself is not very descriptive for what is

actually occurring, a new message is being considered for future

versions of the compiler.