c++initializationglobal-variables

C++ Global and Scoped integers initial values


A Four bytes memory slot is reserved for every defined integer. Uninitialised variable maintains the old value of that slot. hence, the initial value is somehow randomised.

int x = 5; // definition with initialisation

This fact in most C++ compilers as far as I know holds for scoped variables. But, when it comes to global variables. a value of zero will be set.

int x; // uninitialised definition

Why does the C++ Compiler behave differently regarding to the initial value of the global and scoped variables.

Is it fundamental?


Solution

  • The namespace level variables (which means global) belong to static storage duration, and as per the Standard, all variables with static storage duration are statically initialized, which means all bits are set 0:

    §3.6.2/2 from the C++ Standard (n3242) says,

    Variables with static storage duration (3.7.1) or thread storage duration (3.7.2) shall be zero-initialized (8.5) before any other initialization takes place.

    In case of local variables with automatic storage duration, the Standard imposes no such requirement on the compilers. So the automatic variables are usually left uninitialized for performance reason — almost all major compilers choose this approach, though there might be a compiler which initializes the automatic variables also.