Swipe
SwipeSwipe
Swipe Apps

Paths

Motivation

Information

Constants & Type Casting · Lesson 24 of 25

Constants (const)

A free lesson from Swipe Coding · C++, level 2 · updated October 2026

By the Swipe team, founded by Colin · how we make lessons

🤖
Some values should just never change — const makes that a promise. 🔒

Sometimes a value should never change once it's set — think of the number of days in a week, or the maximum number of players allowed in a game. C++ lets you mark a variable as a constant using the const keyword, which tells the compiler this variable's value must never change after it is initialized.

const double PI = 3.14159;
std::cout << PI << std::endl;
Declaring a constant with const — PI can be read, but never reassigned.
🤖
ALL_CAPS names make constants impossible to miss in your code. 🔠

By convention, constant names are often written in UPPER_SNAKE_CASE: every letter capitalized, with underscores separating words, such as MAX_PLAYERS or DAYS_IN_WEEK. This makes constants instantly recognizable, setting them apart at a glance from regular camelCase variables.

const int MAX_PLAYERS = 4;
std::cout << MAX_PLAYERS << std::endl;
MAX_PLAYERS follows the UPPER_SNAKE_CASE convention for constants.
🤖
This is exactly the kind of bug a good constant name prevents. 🎯

If you try to reassign a const variable after it has been initialized, the code will not compile — the compiler catches the mistake before the program ever runs. This is exactly why constants are so useful: they replace unexplained 'magic numbers' scattered through your code with a single, clearly named, protected value. If that value ever needs to change, you update it in exactly one place.

const int MAX_LIVES = 3;
MAX_LIVES = 5; // Compile error: assignment of read-only variable
The compiler stops you from ever changing a const variable's value after it is set.
Fill in the blank

The ____ keyword tells C++ that a variable's value can never be changed after it is initialized.

Quick check

What happens if you try to reassign a variable declared with const?

True or false

A const variable must be given its value at the moment it is declared, since it can never be assigned afterward.

Keep your streak going in Swipe Coding

Swipe through every level of C++ on your iPhone — with XP, stars, streaks, a personal advisor and the full track beyond these free levels.

Get the Swipe apps →