The short answer
In C++, const tells the compiler that a variable, parameter or member function should not change the object it applies to. The compiler checks that promise. A line that would quietly change a value becomes a compile error. That makes code safer to change later and easier to read.
Protecting values that should not change
Many values are set once and then left alone, such as a tax rate or a limit. Marking them const records that intent:
const int max_attempts = 3;
const double tax_rate = 0.07;
max_attempts = 5; // Compile error: the value is read-only
If someone later edits that line by accident, the build fails instead of the program running with a changed value.
Function parameters
Parameters are a common place to use const. If a function only reads its input, a const reference says so and avoids copying large objects:
#include <iostream>
#include <string>
void show_greeting(const std::string& name) {
std::cout << "Hello, " << name << "\n";
}
The caller gets a guarantee that show_greeting won’t change the string it was given. The same idea applies to arrays, and how to pass an array to a function in c covers the details.
Member functions that only read
A const after a member function’s parameter list promises the function won’t change the object:
class Thermostat {
public:
double current() const { return temperature; }
void set(double t) { temperature = t; }
private:
double temperature = 20.0;
};
A const Thermostat object can call current(), but it can’t call set(). Without the const on current(), the compiler would reject the call on a const object even though the function only reads data.
Compile-time values and array sizes
C++ allows a const integer, initialized with a constant value, to be used where the compiler needs a fixed size:
const int rows = 3;
int board[rows][rows] = {};
Where const does not help
const only restricts the names that use it. If an object isn’t const, a non-const name or pointer can still change it. A const reference can’t be used to change the object, but other code can still change the object through a non-const name.
Adding const also doesn’t make a program faster or smaller by itself. Compilers may optimize based on it, but you shouldn’t count on that as the reason to use it.
If you need a value the compiler knows at compile time, use constexpr rather than const. The c const keyword guide covers the difference between them.
When to add const
- Declare a variable
constwhen its value should not change after setup. - Take a parameter as a const reference when the function only reads it.
- Mark a member function
constwhen it doesn’t modify the object.
These habits catch mistakes early, and they tell other readers what the code is meant to do.