15. Use const proactively.
Summary
const is your friend. Immutable values are easier to understand, track, and reason about, so prefer constants over variables wherever it is sensible and make const your default choice when you define a value. It's safe, it's checked at compile time,
and it's integrated with C++'s type system. ...
Discussion
Constants simplify code because you only have to look at where the constant is defined to know its value everywhere. Consider this code:
void Fun( vector<int>& v)
{ //...
const size_t len = v.size();
//... 30 more lines ...
}
When seeing len's definition above, you gain instant confidence about len's semantics throughout its scope (assuming the code doesn't cast away const, which it should not do). It's a snapshot of v's length at a specific point. Just by looking up one line of code, you know len's semantics over its whole scope. Without the const, len might be later modified, either directly or through an alias. Best of all, the compiler will help you ensure that this truth remains true.
...
From: 'C++ Coding Standards: 101 Rules, Guidelines, and Best Practices' by Sutter and Alexandrescu