1.5 — Giving variables a value

📘 Chapter 1⏱ about 1 min read✍️ Beginner friendly
Read one box at a time. No rush.

Two ways to put a value in#

  1. Initialize: give a value when you make the box.
  2. Assign: put a new value in later.
C++
int score = 0;   // initialize: score starts at 0score = 50;      // assign: now score is 50

When you assign, the old value is thrown away.

Brace initialization#

Modern C++ has another way to initialize, using { }:

C++
int lives { 3 };double speed { 2.5 };

This does the same as =, but it is safer. It stops you from losing data by accident:

C++
int a = 4.9;   // compiles, but a is 4 — the .9 is silently lost!int b { 4.9 }; // error: the compiler stops you
Good habit

Prefer { } to initialize variables. It catches mistakes for you.

Empty braces#

{ } with nothing inside gives a sensible starting value. For numbers, that is 0.

C++
int count {};   // count is 0

= means "put into", not "equals"#

In math, = means two things are equal. In C++, = means put the value on the right into the box on the left.

C++
int x { 5 };x = x + 1;   // take x (5), add 1, put 6 back into x

This looks odd in math, but it makes total sense in C++.

Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.