You are here:

C++/C++ on Variable Creation

Advertisement


Question
if(false)
   {
     static int a;
   }
Will the variable "a" created or not ?

Answer
Maybe, and if not then not necessarily for the reasons you might think!

Strictly speaking the variable exists because it is static and static variables exist for the whole of the program duration. It is first zero initialised before any other initialisation. Variables of plain old data (POD) types (meaning primitives such as int - like a in your example - and C-like structs etc.) are static initialised with any given constant expression _before_ its block is first entered. Objects of class types requiring construction are initialised the first time control passes through its declaration, which in this example should variable a have been of such a type would be never.

Because the variable a exists in a part of code that can never be accessed and it is not accessed further a compiler may or may not decide to remove it.

I shall show some variations of your original code and shall number each version. Your original is number 1:

(1)
   if ( false )
   {
       static int a;
   }

In the first variation the test is changed to true:

(2)
   if ( true )
   {
       static int a;
   }

The next variation is to make use of the variable by incrementing it:

(3)
   if ( false )
   {
       static int a;
       a++;
   }

The final variation has both a true test and a use of the variable:

(4)
   if ( true )
   {
       static int a;
       a++;
   }

So we have four versions, on two axis of variation, each with two values: Whether the test is true or false and whether the static variable is used or not.

I tried all four variations with two compilers: the Microsoft Visual C++ 2005 compiler (a.k.a. MSVC++ 8.0) under Windows XP Professional x64 Edition, and the GNU g++ 4.0.2 compiler under SuSE Linux 10.0 x64 version. Neither compiler was set up to produce optimised code: MSVC++ was setup to produce a non optimised 32-bit debug build and g++ to produce default code (i.e. what it produces if you just use: g++ source.cpp). I checked the results by examining the assembler produced by the compilers and seeing where the name of the variable appeared (to help with easy location I changed the variable name to a_a_a_). The table below shows the results.

Note: the table layout is done using very primitive spacing and therefore should be viewed using a mono-spaced font such as Courier (e.g. treat it as code).

   Code variation          g++ code          MSVC++ code
-----------------------------------------------------------------
(1) (false, not used)       No variable a        No variable a          
(2) ( true, not used)      Has variable a        No variable a          
(3) (false,     used)       No variable a       Has variable a          
(4) ( true,     used)      Has variable a       Has variable a          

From the above it is obvious that your original code is most likely to produce code that does not reserve storage for and initialisation of the variable, whereas the final version which uses a true test and makes use of the variable is the most likely to produce code that causes the variable to be allocated and initialised (as would be expected!).

The middle two cases are the interesting ones however.

Variation 2 has a true test, but does not use the variable a. In this case MSVC++ eliminated the variable but g++ did not.

Variation 3 uses the variable but from within a false tested block. In this case the situation is reversed: g++ eliminated the variable but MSVC++ did not!

From this you can see that the reason the compilers eliminated the variable when compiling your example differ: g++ eliminated it because the variable was local to an inaccessible block of code; MSVC++ eliminated it because the variable was not used.

Of course I would expect both compilers to reduce the code for all variations if I requested they optimised the code.

Hope this is of use.  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Ralph McArdell

Expertise

I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.

Experience

My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at http://www.open-std.org/jtc1/sc22/wg21/.

Education/Credentials

©2016 About.com. All rights reserved.