How are local and global variables initialized by default?

Building up on Andrey’s response.

$3.6.2- “Objects with static storage duration (3.7.1) shall be zero-initialized (8.5) before any other initialization takes place.”. In OP, “global_A” and “global_int” have static storage duration. “local_int” and “local_A” have no linkage as these are local objects.

$8.5/5- To zero-initialize an object of type T means:

— if T is a scalar type (3.9), the
object is set to the value of 0 (zero)
converted to T;

— if T is a non-union class type, each
nonstatic data member and each
base-class subobject is
zeroinitialized;

— if T is a union type, the object’s
first named data member89) is
zero-initialized;

— if T is an array type, each element
is zero-initialized;

— if T is a reference type, no
initialization is performed.

$6.7.4/4- “The zero-initialization (8.5) of all local objects with static storage duration (3.7.1) is performed before any other initialization takes place. A local object of POD type (3.9) with static storage duration initialized with constant-expressions is initialized before its block is first entered. An implementation is permitted to perform
early initialization of other local objects with static storage duration under the same conditions that an implementation is permitted to statically initialize an object with static storage duration in namespace scope(3.6.2). Otherwise such an object is initialized the first time control passes through its declaration; such an object is considered initialized upon the completion of its initialization. If the initialization exits by throwing an exception, the initialization is not complete, so it will be tried again the next time control enters the declaration. If control re-enters the declaration (recursively) while the object is being initialized, the behavior is undefined.”

EDIT 2:

$8.5/9- “If no initializer is
specified for an object, and the
object is of (possibly cv-qualified)
non-POD class type (or array thereof),
the object shall be
default-initialized; if the object is
of const-qualified type, the
underlying class type shall have a
user-declared default constructor.
Otherwise, if no initializer is specified for a nonstatic object, the
object and its subobjects, if any,
have an indeterminate initial
value90)
; if the object or any of
its subobjects are of const-qualified
type, the program is ill-formed.”

In general, you want to read up these sections along with $8.5 for good hold on this aspect.

Leave a Comment