Skip to content
Theory · Variables and Types · lesson 2 of 10

Initialization: =, () and {}

The value a variable gets in its declaration is its initial value, and this step is called initialization. If the value does not suit the variable's type, the compiler converts it on its own, possibly losing part of it:

C++
#include <iostream>

int main() {
    double price = 2.9;
    int whole = price;
    std::cout << whole << '\n';  // 2
}

An int holds only whole numbers, so the fraction 0.9 is dropped, with no rounding. The compiler reports neither an error nor a warning, and the program prints 2.

Three forms

An initial value can be written in three ways:

C++
int a = 5;
int b(5);
int c{5};
std::cout << a << ' ' << b << ' ' << c << '\n';  // 5 5 5

For an int and 5, all three lines do the same thing. They differ in how they treat a value that does not fit. = and parentheses convert it, as in the example above.

Empty braces set the value to zero: int total{}; means the same as int total{0};. The = form is more familiar and the most common, while the next example shows what makes braces better.

Braces against narrowing

A conversion that may lose part of a value is called a narrowing conversion. It happens when a fractional number goes into an integer type, or when a number does not fit in the new type. What matters is not the type's size in bytes but whether part of the value can be lost. Braces forbid narrowing:

C++
int count{2.5};  // ✗
TEXT
error: type 'double' cannot be narrowed to 'int' in initializer list [-Wc++11-narrowing]

This is a compile error: the program does not build until the value is fixed. Braces let through a constant that fits the new type exactly: double ratio{2}; compiles. int whole{price}; from the first example is narrowing too: price may hold a fractional number. That makes braces the strictest of the three forms: they catch a type mistake at once.

Common mistake

A variable is declared without an initial value and then read:

C++
int total;
total = total + 5;  // ✗
TEXT
warning: variable 'total' is uninitialized when used here [-Wuninitialized]

A variable declared inside a function without an initial value has an indeterminate value. Reading such a value is undefined behavior: the C++ standard does not say what the program will do. The compiler only warns, so give the value right away: int total{0}; or int total{};.