1. Goals
Use
constfor values that should stay unchanged and for read-only access.Distinguish
const int*fromint* constin pointer declarations.Explain why a read-only reference can still observe changes to the original object.
2. Prerequisites
You have studied initialization/assignment, addresses/pointers, and references.
You know that &available obtains an address, *pointer accesses the pointed-to
object, and int& alias = available; names the same object another way.
The examples continue to use C++17 without manual memory allocation.
3. Explanation
A fixed value and read-only access
const int limit{10}; creates an integer with the initial value 10 that
cannot be reassigned. The compiler rejects limit = 12;. Initialize a
const integer when declaring it; you cannot leave it blank and assign later.
const does not mean every value must be calculated during compilation.
You can obtain data while the program runs, validate it, and use the resulting
value to initialize a const variable. The concern here is permission to
modify after initialization, not necessarily computation before execution.
With int available{8}; const int& observed = available;, observed is
a read-only alias of available, not a new integer containing a copy of 8.
You cannot write observed = 9;, but available = 9; is valid because
the original object was not declared const. Reading observed then yields 9.
A reference to const therefore restricts access through that reference;
it does not freeze the whole program or every other name for the data.
To retain a snapshot, use a copy such as const int snapshot = available;.
Later changes to available do not update snapshot. This distinguishes
a read-only copy from a read-only alias.
The C++17 rules for const
describe multiple access paths to one object with different permissions.
Does const apply to the pointer or its target?
These two similar declarations restrict different operations:
const int* selected = &available;: you cannot modify the integer throughselected. You can assignselected = &reserve;to select another object.int* const fixed = &available;: you cannot reassign the address infixed. You can write*fixed = 7;to modify the integer it points to.
In the first form, const belongs to the pointed-to int type. In the
second, const follows * and belongs to the pointer variable itself.
int const* means the same as const int*. The form const int* const
combines both restrictions: neither replace the stored address nor modify
the integer through that pointer.
See the C++17 pointer declaration rules.
A const int* can point to either an ordinary int or a const int.
Pointing it at an ordinary int does not make that object const; it only
restricts access through this pointer. Conversely, you cannot initialize
an int* from the address of a const int: that would grant write permission
the object does not allow. Preserve the appropriate const-qualified type.
In the example, fixed and selected initially both point to available.
*fixed = 7; is valid because available is a modifiable integer.
Reading *selected afterward also produces 7, even though assignment
through selected is forbidden. A fixed pointer does not imply fixed data.
Initializing pointers and handling absent data
When no object has been selected, write const int* optional = nullptr;.
nullptr represents a pointer that does not point to an object. Read
*optional only when the pointer is known to point to a suitable live object.
The example checks if (optional != nullptr) before each read through it.
Do not write const int* optional; and then compare it with nullptr:
the local pointer is uninitialized, so even the comparison reads an
indeterminate value. const neither initializes a pointer nor makes it safe.
A non-null check handles the case where no object has been selected. It does not detect a pointer invalidated by its object's destruction. All targets in the example remain alive while accessed; the scope and lifetime lesson examines this requirement more closely.
4. Runnable example
Save as main.cpp and compile with C++17. No input is needed.
#include <iostream>
int main() {
int available{8};
const int limit{10};
const int& observed = available;
const int* selected = &available;
int* const fixed = &available;
std::cout << "Limit: " << limit << '\n';
std::cout << "Observed before: " << observed << '\n';
available = 9;
std::cout << "Observed after: " << observed << '\n';
*fixed = 7;
std::cout << "Fixed target: " << *selected << '\n';
const int reserve{4};
selected = &reserve;
std::cout << "Selected reserve: " << *selected << '\n';
const int* optional = nullptr;
if (optional != nullptr) {
std::cout << "Optional: " << *optional << '\n';
} else {
std::cout << "Optional: none" << '\n';
}
optional = &available;
if (optional != nullptr) {
std::cout << "Optional now: " << *optional << '\n';
}
return 0;
}Exact output:
Limit: 10
Observed before: 8
Observed after: 9
Fixed target: 7
Selected reserve: 4
Optional: none
Optional now: 7Neither observed, selected, nor fixed creates a copy of available.
A pointer has its own variable storing an address; a reference is an alias.
Redirecting selected to reserve does not redirect fixed.
5. Common mistakes
Treating
const int&as a snapshot: it remains an alias of the original object.Confusing
const int*withint* const: consider address changes and data changes separately.Adding
constbut skipping initialization, null checks, or lifetime requirements.Casting away
constjust to make a modification compile: fix the data interface or make a copy when an independent modification is needed.Assuming const protects every object reachable through an object's pointers.
int* constalready shows a fixed pointer whose integer target remains modifiable.
6. Practice
Change
available = 9;toavailable = 6;.Observed aftershould become6;Fixed targetandOptional nowremain7because of the later assignment.Add
const int snapshot = available;beforeavailable = 9;, then printsnapshotafter the assignment. Expect8, whileobservedis9at that point.In a scratch copy, try each line separately:
observed = 2;,*selected = 2;, andfixed = nullptr;. Compilation must reject all three; explain which permission each violates.Replace the final
optional = &available;withoptional = nullptr;. The program remains safe and no longer prints theOptional nowline.
7. Self-check
With
int score{3}; const int& view = score; score = 5;, what doesviewread? Answer:5. Assignment throughviewis forbidden, but changingscoreis valid.Which declaration lets you select another target, and which lets you change the integer:
const int* porint* const p? Answer: the first permits pointer reassignment but no modification through*p; the second fixes the address but permits changing*pwhen it points to a valid modifiable object.Is
const int* p; if (p != nullptr)insidemainalready safe? Answer: no. Initializep, for example tonullptr, before even comparing it. After assigning an address, also ensure the target stays alive whenever accessed.
Sample code
Source file
cpp98_foundation/09_const_correctness/main.cpp
#include <iostream>
int main() {
int available{8};
const int limit{10};
const int& observed = available;
const int* selected = &available;
int* const fixed = &available;
std::cout << "Limit: " << limit << '\n';
std::cout << "Observed before: " << observed << '\n';
available = 9;
std::cout << "Observed after: " << observed << '\n';
*fixed = 7;
std::cout << "Fixed target: " << *selected << '\n';
const int reserve{4};
selected = &reserve;
std::cout << "Selected reserve: " << *selected << '\n';
const int* optional = nullptr;
if (optional != nullptr) {
std::cout << "Optional: " << *optional << '\n';
} else {
std::cout << "Optional: none" << '\n';
}
optional = &available;
if (optional != nullptr) {
std::cout << "Optional now: " << *optional << '\n';
}
return 0;
}