Handmade Hero»Forums»Code
Patrick Lahey
67 posts
From C Standard, uninitialized globals set to zero
Sorry if this has already been answered, I'm a couple of weeks behind in the videos. Someone mentioned in one of the Q&As that globals (not just statics) were initialized to zero and Casey wanted proof from the standard, so here it is. Warning, take a hit almond milk before continuing - this is something only "language lawyers" will enjoy...

Summary: globals have "static storage duration" (yes, static is way overloaded) and uninitialized variables of that type are cleared to zero automatically.

The final standards are not available for free, but late drafts are (see iso-9899.info). I'm using the C standard even though we Casey is technically using C++.

From 6.2.1, item 4 (define file scope):


... If the declarator or type specifier that declares the identifier appears outside of any block or list of parameters, the identifier has file scope, which terminates at the end of the translation unit.

From 6.7.1, item 1 (define storage-class specifier):

storage-class-specifier:
typedef
extern
static
auto
register

From 6.2.2, item 5 (establish globals have external linkage):

... If the declaration of an identifier for an object has file scope and no storage-class specifier, its linkage is external.

From 6.2.4, item 1 (establish the different storage durations):

An object has a storage duration that determines its lifetime. There are three storage
durations: static, automatic, and allocated.

From 6.2.4, item 3 (establish that globals, which have external linkage, have static storage duration):

An object whose identifier is declared with external or internal linkage, or with the
storage-class specifier static has static storage duration. Its lifetime is the entire
execution of the program and its stored value is initialized only once, prior to program startup.

From 6.7.8, item 10 (establish uninitialized static storage duration types get set to zero):

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.

That was a bit painful... :)
Neil Blakey-Milner
45 posts
From C Standard, uninitialized globals set to zero
From memory, the short way to figure which ones are initialised (besides the "Never assume" rule) is that only things that have no run-time cost to initialise are initialised. Stack allocations are not initialised, since they would actually entail work. Globals and static variables in functions have no cost to initialise - they are stored in the data segment.