How to Initialize C++ Variables

C++ Variable Initialization

In C++, initializing a variable gives it an initial value when you declare it. This differs from assignment, which replaces the value of an existing object.

Initialization Methods

FormNameWhat happens
int a;Default initializationFor local variables of fundamental (built-in) types (int, double, pointers), it does not set an initial value. The variable starts with an indeterminate value. Reading a before you assign a value causes undefined behavior. (Note: the compiler zero-initializes global and static variables).
int b = 5;Copy initializationInitializes b with 5. Although = usually assigns a value, here it is part of the declaration. It allows implicit narrowing conversions (for example, it truncates 6.4 to 6).
int c(6);Direct initializationInitializes c with 6 using parentheses. For classes, it directly calls the matching constructor. It also allows implicit narrowing conversions (for example, it truncates 6.4 to 6).
int d{7};Direct-list initializationInitializes d with 7 (C++11 introduced this as uniform initialization). It rejects narrowing conversions and causes a compilation error if you initialize an int with 6.4.
int d = {7};Copy-list initializationWorks like int d{7}; and rejects narrowing conversions, but it does not call explicit constructors.
int e{};Value initializationFor fundamental types like int, it zero-initializes the variable to 0. For classes, it calls the default constructor.

Comparison and When to Use Each Form

Several syntaxes produce the same result for fundamental types, but each form has a specific purpose in modern C++:

1. List / Uniform Initialization (int d{7}; and int e{};) — The Default Choice

  • Comparison: C++11 introduced this safe and consistent form. It works for any type (fundamental types, aggregates, structs, classes, and containers) and rejects narrowing conversions.
  • When to use:
    • Use this form by default in modern C++ code.
    • Use Type var{value}; when you know the initial value and want to prevent accidental data truncation.
    • Use Type var{}; to initialize the variable with a safe default value (0, nullptr, false, or the default constructor). This avoids indeterminate memory values and the Most Vexing Parse.

2. Copy Initialization (int b = 5;) — Traditional and Readable

  • Comparison: This syntax comes from C and is familiar to most readers. However, it allows silent narrowing conversions on fundamental types and cannot call explicit constructors.
  • When to use:
    • Use it with simple scalar types (int, bool, double) when your codebase prefers =.
    • Use it with auto type deduction (for example, auto x = 5; in Almost Always Auto style), where the right-hand expression determines the type.

3. Direct Initialization with Parentheses (int c(6);) — Specific Constructor Cases

  • Comparison: It calls constructors directly (including explicit constructors), but it allows narrowing conversions. Without arguments (Type c();), it triggers the Most Vexing Parse.
  • When to use:
    • Use it when a class overloads std::initializer_list and you need a different constructor. For example, std::vector<int> v(5, 10); creates 5 elements with value 10, whereas std::vector<int> v{5, 10}; creates 2 elements (5 and 10).
    • Use it inside forwarding functions or generic factories in pre-C++20 code.

4. Copy-List Initialization (int d = {7};) — Aggregates and Function Returns

  • Comparison: It combines = with the brace protection {} against narrowing conversions, but it cannot call explicit constructors.
  • When to use:
    • Use it to initialize aggregate structs or arrays: Point p = {10, 20};.
    • Use it when you want the compiler to reject explicit conversions.

5. Default Initialization (int a;) — Avoid, Except for Performance or Immediate Input

  • Comparison: This is the only form that leaves local fundamental types with an indeterminate value (garbage memory). For classes (such as std::string s;), it calls the default constructor. For fundamental types, it often causes bugs.
  • When to use:
    • Avoid by default.
    • Use it only when an input function populates the variable on the next line (for example, int x; std::cin >> x;).
    • Use it in performance-critical code (such as large buffers) when you overwrite the memory immediately and want to skip zero-initialization.

Quick Decision Summary

SituationRecommended FormExample
Known initial value (general rule)Direct-list {value}int age{25};
Must start at zero or emptyValue {}int counter{}; / int* ptr{};
Constructor conflicts with initializer_listDirect (args)std::vector<int> v(100, 0);
With autoCopy = or {}auto total = computeTotal();
Read from std::cin or an out-parameterValue {} (or default if immediate)int input{}; std::cin >> input;

Key Differences and Pitfalls

For simple types like int, forms b, c, and d produce the same value. However, the differences matter in four cases:

1. Narrowing Conversions

Brace initialization {} prevents implicit conversions that could lose data at compile time:

int x1 = 3.5;  // Compiles (with warning): truncates value to 3
int x2(3.5);   // Compiles (with warning): truncates value to 3
int x3{3.5};   // Compilation ERROR: narrowing conversion from double to int

2. explicit Constructors

For user-defined types (class or struct), copy initialization (=) cannot call explicit constructors. Direct initialization (() or {}) can call them:

struct Box {
    explicit Box(int size) {}
};

Box b1(10);       // OK: direct initialization
Box b2{10};       // OK: direct-list initialization
// Box b3 = 10;   // ERROR: constructor is explicit
// Box b4 = {10}; // ERROR: copy-list initialization does not accept explicit

3. Most Vexing Parse (The Empty Parentheses Problem)

When you use empty parentheses, the compiler parses the line as a function declaration, not a variable definition:

int f();   // Declares a function named 'f' returning int (does NOT create a variable!)
int g{};   // Creates a variable 'g' initialized to 0

4. std::initializer_list Priority

When a type has a std::initializer_list constructor (such as std::vector), brace initialization {} selects that constructor first:

#include <vector>

std::vector<int> v1(5, 10); // Creates a vector with 5 elements, all of value 10
std::vector<int> v2{5, 10}; // Creates a vector with 2 elements: {5, 10}

Best Practices in Modern C++

General Rule (C++ Core Guidelines — ES.23): Prefer the {}-initializer syntax (list-initialization).

  • When you know the initial value: use int x{value};. It prevents narrowing conversions.
  • When you need a default or zero value: use int x{};. It zero-initializes the variable and avoids the Most Vexing Parse.
  • When you use auto: prefer auto x = value; or auto x{value};. Since C++17, auto x{5}; deduces int, whereas auto x = {5}; deduces std::initializer_list<int>.

References

https://www.learncpp.com/cpp-tutorial/variable-assignment-and-initialization/ https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es20-always-initialize-an-object