Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
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.

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 braces

Brace 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?"

Checking three declarationsStep 1 of 4
  1. int lives = 3;

    The value is an int and the variable is an int. Nothing to convert.

Drills

Answer fast — trust the rule.

quick drill

What happens with int lives = 3; lives = "three";?

quick drill

What does int coins{2.5}; do?

quick drill

What does int coins = 2.5; do?

quick drill

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.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainBraces as a safety net

In Rocket Run, int coins = 2.5; compiles and quietly stores 2, while int coins{2.5}; refuses to compile. Explain what static typing means, why the two lines behave differently, and which style you would use.