const Variables and Parameters
Protect data from change.
Declaring const Variables
A const variable cannot be modified after initialization. The compiler enforces this, catching accidental writes.
#include <iostream>
int main() {
const int maxUsers = 100;
// maxUsers = 200; // ERROR
std::cout << maxUsers << "\n";
}const Function Parameters
Marking a by-value parameter const prevents the function body from altering its local copy — a documentation and safety aid.
#include <iostream>
int doubled(const int n) {
// n = 0; // ERROR
return n * 2;
}
int main() { std::cout << doubled(21) << "\n"; }All lessons in this course
- const Variables and Parameters
- const Member Functions
- constexpr and Compile-Time
- consteval and constinit