Skip to the workspace
Pebellslearn by building
Data Types  ›  Lesson

Static Typing

Static Typing 12 minIn 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.

cpp / Static Typing

Explore each scene at your own pace.

01 · The rule

The rule

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 braces

Brace initialisation forbids narrowing, meaning conversions that can lose data. That turns a silent bug into a compile error.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.