FIX: Global Constants Are Initialized in Reverse Order (313847)



The information in this article applies to:

  • Microsoft Visual C++ .NET (2002)

This article was previously published under Q313847

SYMPTOMS

Global constants can be initialized in the wrong order if you use global optimizations (/Og option) and pre-compiled headers.

The program initializes the constants in the reverse order of how they appear in the code, which is counter-intuitive and which may cause unexpected results.

RESOLUTION

To work around this behavior, disable global optimizations or compile by using the Disable Optimization option (/Od).

STATUS

Microsoft has confirmed that this is a bug in the Microsoft products that are listed at the beginning of this article. This bug was corrected in Microsoft Visual C++ .NET (2003).

MORE INFORMATION

Steps to Reproduce the Behavior

  1. Run <drive:><path>\Microsoft Visual Studio .NET\Vc7\bin\vsvars32.bat.
  2. Create a file named Main.cpp, and then add the following code:
    #include "main.h" 
    #include "stdio.h"
    #define  VC7BUG 
    int main() 
    {  
    // The constants are initialized in the reverse order of how they are used.
    #ifdef   VC7BUG         // 
        float one = Pie1;   // Pie1 = 3.14 -initialized second since used first.
        float two = Pie2;   // Pie2 = 0    -initialized first since used second. 
    #else 
        float two = Pie2;   // Pie2 = 6.28 -initialized second since used first.
        float one = Pie1;   // Pie1 = 3.14 -initialized first since used second. 
    #endif
        if ((int)(one+two) < 9){
    	 printf("the values are incorrect");
    	 return 0;
        }else{
             printf("the values are correct");
             return 1;
        }
    }
    					
  3. Create a file named T.cpp, and then add the following code:
    #include "main.h"
    					
  4. Create a file named Main.h, and then add the following code:
    #include <stdio.h>
    const float Pie3  = 3.14f; 
    const float Pie1 = Pie3*1;   // "Pie1" depends on "Pie" 
    const float Pie2 = Pie1*2;   // "Pie2" depends on "Pie1" 
    					
  5. Run the following code from a command prompt:
    cl  /Ycmain.h /Og /c t.cpp
    
    cl /Yumain.h /Og main.cpp
    
    main.exe
    					
The following message is displayed:
the values are incorrect

Modification Type:MajorLast Reviewed:4/11/2003
Keywords:kbfix kbbug kbCompiler kbpending KB313847