Const Parameters and Immutability
What you'll learn: How to protect function parameters from accidental changes by marking them as constant.
The Core Idea
When you pass a parameter to a function, you might want to guarantee that the function won't modify that data. By declaring a parameter as const (constant), you tell both the compiler and other programmers: "This function only reads this value—it will never change it."
Think of it like lending someone your favorite book with a clear rule: "You can read it, but don't write in the margins or bend the pages." The const keyword enforces that rule at compile-time.
Why This Matters
Using const parameters provides two key benefits:
- Safety: The compiler prevents accidental modifications. If your function tries to change a const parameter, you'll get an error before the code even runs.
- Clarity: Other programmers (including future-you) can see at a glance that the function won't alter the input, making code easier to understand and trust.
When to Use Const Parameters
- When passing data by reference (remember pass-by-reference from earlier?) but you only want to read it, not modify it
- For large data structures where you want reference efficiency without mutation risk
- Any time a function's purpose is to inspect, compute from, or report on data without changing it
Simple Example Pattern
// Without const: function COULD modify the parameter
void printValue(int& x) {
x = 100; // Allowed but maybe unintended!
}
// With const: function CANNOT modify the parameter
void printValue(const int& x) {
// x = 100; // Compiler error! Protected.
}
Key Takeaway: Const parameters act as a safety lock, preventing functions from modifying input data and making your intentions crystal-clear to anyone reading your code.