PRB: Bad Code May Be Generated for Nested Loops with /Ol

ID Number: Q66216

6.00 6.00a 6.00ax | 6.00 6.00a

MS-DOS | OS/2

buglist6.00 buglist6.00a buglist6.00ax fixlist7.00

Summary:

SYMPTOMS

The code below illustrates a problem in C versions 6.0, 6.0a, and

6.0ax in using loop optimization (/Ol) with nested loops.

With loop optimizations disabled, the compiler calculates the value

of x for each iteration of the loop and produces the correct result.

When loop optimizations are turned on, the compiler initializes the

value of x and subtracts it by 10 on each loop iteration. The problem

occurs here with the miscalculation of x when variable i increments.

RESOLUTION

The only workaround is to compile without loop optimizations, which

can be done in the following ways:

1. Do not use the /Ol option.

-or-

2. Insert the #pragma optimize statement in the code to turn off loop

optimization for the particular function.

STATUS

Microsoft has confirmed this to be a problem in C versions 6.0,

6.0a, and 6.0ax. This problem was corrected in C/C++ version 7.0.

Sample Code

-----------

#include<stdio.h>

void main(void)

{

int i, j, x;

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

{

for (j=0; j<4; j++)

{

x=(i*4+3-j)*10;

printf("%d\n", x);

}

}

}

The following table demonstrates the output when the code above is

compiled with and without loop optimizations:

Correct Output Without /Ol Incorrect Output with /Ol

-------------------------- -------------------------

30 30

20 20

10 10

0 0

70 -10

60 -20

50 -30

40 -40