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 (see Item 14), and it’s integrated with C++’s type system. Don’t cast away const except to call a const-incorrect function (see Item 94).

Discussion

Constants simplify code because you only have to look at where the constant is defined to know its value everywhere. Consider this code:

image

When seeing len’s definition above, you gain instant confidence about len’s semantics ...

Get C++ Coding Standards: 101 Rules, Guidelines, and Best Practices now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.