Variable initialization

A quick comparison of C++ initialization forms.

At a glance

Syntax Name Result
int x; Default initialization No initial value is provided. For a local int, the value is indeterminate.
int x = 5; Copy initialization Initializes x with 5. Allows narrowing conversions.
int x(5); Direct initialization Initializes x with 5. Allows narrowing conversions.
int x { 5 }; Direct-list initialization Initializes x with 5 and rejects narrowing conversions.
int x {}; Value initialization Initializes x to zero.
int count { 5 };
int total {}; // 0

Important differences

No initializer

int x;

For a local fundamental type, no usable initial value is provided. Reading x before giving it a value results in undefined behavior.

Narrowing conversions

Brace initialization rejects a value that cannot be represented safely by the destination type.

int a = 4.5;  // allowed: a becomes 4
int b(4.5);   // allowed: b becomes 4
int c { 4.5 }; // error: narrowing conversion

The parentheses trap

int x();

This declares a function named x that takes no arguments and returns an int. It does not define an integer variable.