why only Global varible Initialized by compiler


hi Guise

i want to know why only Global Variable are initialized by compiler ,

i don't get answer to this question in many books can you help me ?
Last edited on
Uh... Globals aren't automatically initialized, either.

EDIT: Except for objects.
Last edited on

I'm new in c++ programming

when i declare any global variable & print it (without initialize ) it show zero

but local variable show some random value (may be bit pattern of previous

memory usage) , can any one tell me why only global variable are set to

zero by compiler ? ( I'm using visual c++ 2008 Express edition)

In principle, a variable defined outside any function (that is, global, namespace, and class static variables) is initialized before main() is invoked. Such nonlocal variables in a translation unit are initialized in their declaration order (§10.4.9). If such a variable has no explicit initializer, it is by default initialized to the default for its type (§10.4.2). The default initializer value for built-in types and enumerations is 0. [...] There is no guaranteed order of initialization of global variables in different translation units. Consequently, it is unwise to create order dependencies between initializers of global variables in different compilation units. In addition, it is not possible to catch an exception thrown by the initializer of a global variable (§14.7). It is generally best to minimize the use of global variables and in particular to limit the use of global variables requiring complicated initialization.


-Bjarne Stroutrup, The C++ Programming Language
Last edited on

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then:
— if it has pointer type, it is initialized to a null pointer;
— if it has arithmetic type, it is initialized to (positive or unsigned) zero;
— if it is an aggregate, every member is initialized (recursively) according to these rules;
— if it is a union, the first named member is initialized (recursively) according to these rules.
C Standard

Globals and statics are intialised to zero, unless they're of user defined types. Auto variables are not initialised at all, again unless they're of user defined types.
Topic archived. No new replies allowed.