Microsoft KB Archive/313847

= FIX: Global Constants Are Initialized in Reverse Order =

Article ID: 313847

Article Last Modified on 4/11/2003

-

APPLIES TO


 * Microsoft Visual C++ .NET 2002 Standard Edition

-



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).



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

cl /Yumain.h /Og main.cpp

main.exe </li></ol>

The following message is displayed:

the values are incorrect

Keywords: kbbug kbfix kbpending kbcompiler KB313847

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.