Static Typing
In C++ every variable's type is fixed at compile time, so the compiler can reject type mistakes and choose exact machine instructions before the program runs.
Distinguish a value's declared type from its changing runtime contents.
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.