1.5 — Giving variables a value
Read one box at a time. No rush.
Two ways to put a value in#
- Initialize: give a value when you make the box.
- Assign: put a new value in later.
C++
int score = 0; // initialize: score starts at 0score = 50; // assign: now score is 50When 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 youGood 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 xThis looks odd in math, but it makes total sense in C++.
Tip: press ← / → to move between lessons, / to search.