Lesson 22 +10 XP

Variable Assignment and Initialization

Variable Assignment and Initialization

Now that we have variables, let's put values in them. There are two different ways: assignment and initialization.

Assignment (copy)

Assignment copies a value into a variable after it already exists. The variable keeps its old value until we overwrite it:

int x;     // created, but empty
x = 5;     // assignment: copy 5 into x
x = 7;     // assignment: now x holds 7

We use the = sign, and the statement ends with a semicolon.

Initialization

Initialization gives a variable its value at the moment it is created - in the same statement as the declaration. An object without initialization has no value yet.

C++ offers several styles. These all do the same job:

int a = 5;        // copy initialization
int b(5);         // direct initialization
int c { 5 };      // list (brace) initialization
int d { };        // brace-initialized to 0
  • Copy initialization int a = 5; - the classic style.
  • Direct initialization int b(5); - uses parentheses.
  • List (brace) initialization int c { 5 }; - modern and safe; it refuses to silently lose data (more on that later).
  • An empty brace int d { }; gives the variable a "zero value".

The recommended way

Modern C++ prefers brace initialization int width { 5 };. It's more consistent than the older styles and prevents a whole class of bugs where data gets quietly lost.

TL;DR

  • Assignment copies a value into an existing variable: x = 5;.
  • Initialization sets the value when the variable is born.
  • Styles: copy int a = 5;, direct int b(5);, brace int c { 5 };.
  • Prefer brace initialization: int width { 5 };.