#010 – The modern way of variable initialization

Defining a variable is called definition.

Giving a variable a value is called assignment.

Initialization merges these two instructions into one statement. E.g. int x { 11 };

This is the modern way of variable initialization.

The historical way is via copy-initialization. E.g. int x = 11;

Copy-initialization has lost support in modern C++ due to being less efficient than other forms of initialization for some complex types.

The pros of list initialization {}

The syntax is clear. When you see curly braces, you immediately recognize that list initialization is occurring.

A special advantage of list-initialization is it forbids narrowing conversions. This is when you attempt to assign a value that doesn’t match the variable type.

int w1 { 4.5 }; // compile error: list-init does not allow narrowing conversion

Thus, list-initialization makes our programs more error-proof.

List initialization is the modern way of initialization

This is because the creator of C++ and a C++ expert said so. See ES.23 under ES: Expressions and Statements

Other benefits:

  1. Allows us to more cleanly initialize multiple variables in a single line
int x = 5, y = 11, z = 12; // Standard initialization
int x{5}, y{11}, z{12};    // List initialization (Uniform Initialization)
  1. Used to cleanly initialize a struct
// Struct definition
struct Player {
    int id;
    double health;
    int score;
};

// Let's list initialize our struct
Player hero{1, 95.5, 1200};

// Traditional way is:
Player p;
p.id = 1; p.health = 95.5; p.score = 1200;

Leave a Reply

Your email address will not be published. Required fields are marked *