Static Typing
A Rocket Run coin pickup is worth 2.5 points in a bonus round, and a teammate stores it in an int. Half a point vanishes without a sound. C++ could have warned them, if they had asked in the right way. Understanding static typing is understanding what the compiler checks for you, and how to make it check more.
The rule
Every variable's type is fixed at compile time and never changes.
Once you declare int lives, lives is an int for its entire life. The compiler uses that knowledge to reject mistakes and to pick exact machine instructions.
The fundamental types you will use most:
| Type | Holds | Example |
|---|---|---|
bool |
true or false | bool alive = true; |
char |
one character | char grade = 'A'; |
int |
whole numbers | int lives = 3; |
double |
numbers with a fraction | double speed = 4.5; |
std::string |
text | std::string name = "Nova"; |
Sizes are only partly fixed by the standard: an int is at least 16 bits and is 32 bits on almost every desktop system. When the exact width matters, such as in a save file, use std::int32_t or std::int64_t from <cstdint>.
C++ still performs some implicit conversions between number types, and some lose information:
int coins = 2.5; // compiles; coins is 2 (fraction dropped)
int coins2{2.5}; // error: narrowing conversion inside bracesBrace initialisation forbids narrowing, meaning conversions that can lose data. That turns a silent bug into a compile error.
The shortcut
Brace-initialise, and let the compiler guard you. Before trusting a line, ask: "Does the value's type match the variable's type? If not, could the conversion lose something?"
int lives = 3;
The value is an int and the variable is an int. Nothing to convert.
Drills
Answer fast — trust the rule.
What happens with int lives = 3; lives = "three";?
What does int coins{2.5}; do?
What does int coins = 2.5; do?
Which type is guaranteed to be exactly 32 bits wide?
Remember
- Every variable's type is fixed at compile time and never changes.
- Shortcut: brace-initialise and let the compiler guard you.
- Trap:
=silently narrows a double into an int; braces refuse.
