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
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;
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;
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 ____ keyword tells C++ that a variable's value can never be changed after it is initialized.
What happens if you try to reassign a variable declared with const?
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 →