Search⌘ K
AI Features

Constants, Type Inference, and Initialization Styles

Explore how to define immutable values with const, simplify code using type inference with auto, and enhance safety through uniform initialization. This lesson teaches you foundational C++ techniques to write clean, robust code and avoid common errors such as magic numbers and narrowing conversions.

We have already learned how to create variables to store values. But some data, like the value of Pi or a fixed configuration setting, should never change after it is created. Additionally, as our programs expand, manually specifying complex data types can become tedious and prone to errors. In this lesson, we will adopt modern practices to make our code safer using constants, cleaner using type inference, and more robust using uniform initialization.

The power of immutability

By default, variables in C++ are mutable, meaning we can overwrite their values as many times as we like. While flexibility is useful, it is also a source of bugs. If a variable representing the "maximum number of players" is accidentally changed in the middle of a game, the program enters an invalid state.

To prevent this, we use the const keyword. This tells the compiler, "This variable is read-only. Once it is created, it cannot be changed." To declare a constant, we follow this syntax:

const <type> <name> = <value>;

Look at an example below.

C++ 23
#include <iostream>
int main() {
const int value = 5; // Define constant
std::cout << "Constant: " << value;
// Attempting to change a constant causes a compile-time error
// value = 100;
return 0;
}
  • Line 5: We declare value as a constant with the const keyword. It must be initialized right here.

  • Line 6: We print the value on to the console.

  • Line 9: If we uncomment this line, the compiler strictly forbids the assignment. This guarantees that value is always 5, no matter how complex the program becomes.

A const variable must be initialized immediately when it is declared. You cannot declare const int x; and assign it later, because "later" would be a modification.

The “Magic Number” problem

A common beginner mistake is using "magic numbers," raw numeric literals scattered throughout the code.

// Bad Practice: What does 60 mean? Seconds? Frames? Speed?
int total = 60 * 5;

Using const allows us ...