C++ Zero Initialization | The “All Bits Zero” First Step

C++ Zero Initialization | The “All Bits Zero” First Step

이 글의 핵심

Zero initialization is the phase that clears static storage to zero before dynamic initialization. Do not assume locals are zero—use `T{}` or assign before read.

What is zero initialization?

Zero initialization sets the object’s initial value to zero (or null pointer / false as appropriate). Static storage duration objects get it automatically before dynamic initialization. For automatic locals, use T{} or value initialization—do not wait for zero init.

int global;        // 0 (static duration)

static int s;      // 0

void func() {
    static int x;  // 0
    int y;         // indeterminate (automatic)
}

Typical results

TypeZero-init result
Integer types0
Floating0.0
boolfalse
Pointersnull pointer value
Arrayseach element zero-initialized

Who gets it automatically?

  • Static storage duration: namespace scope, static locals, thread_local in many cases
  • Happens before dynamic initialization (constructors, etc.)

Relation to other phases

Static init is described in stages:

  1. Zero initialization — bits cleared
  2. Constant initializationconstexpr / compile-time constants
  3. Dynamic initialization — runtime before main() (ordering between TUs can bite)

Value initialization for int x{} includes zero-related steps for scalars; default initialization int x for locals does not.

Locals vs static

int g;                    // static duration → zero first

void f() {
    static int s;         // zero
    int a;                // automatic → indeterminate
    thread_local int t;   // zero-initialized
}

Common mistake: assuming locals are “almost zero” like globals—they are not.

Classes

For class types with static storage, zero init may zero out trivial subobjects before constructors run. Non-trivial types still need proper construction—do not rely on “all bits zero” as a valid state for arbitrary C++ objects.

Initialization order example

int g1;                  // zero, then possibly dynamic init
constexpr int g2 = 50; // constant init
int g3 = compute();      // dynamic before main()

FAQ

Q1: When does zero init happen?
A: For static/thread-local as part of program startup; not for ordinary automatic locals.

Q2: Are locals zero-initialized?
A: No—use int x{} or assign before use.

Q3: Class members?
A: Static data members: zero before dynamic init; instance members of automatic objects follow default/value rules.

Related: Value initialization, Constant initialization, Aggregate initialization.

One line: Zero initialization clears static storage early; locals need explicit init.


  • C++ Value initialization
  • C++ Default initialization
  • C++ Constant initialization
  • C++ Initialization order

Keywords

C++, zero initialization, static initialization, BSS, globals.


  • C++ Dynamic initialization
  • C++ Aggregate initialization