Constants
Lesson outline
Understanding Constants
Constants are objects whose values cannot be changed after initialization. In C++, const makes an object read-only. This improves safety and clarity by preventing accidental modification.
const does not necessarily mean compile-time: a const object can be initialized at runtime. Use constexpr (and, for initialization-only guarantees of static storage, constinit) for compile-time contexts.
Declaring Constants
Use the const keyword for read-only objects. Use constexpr when you need a compile-time constant expression (e.g., for non-type template parameters, std::array sizes, case labels).
Constant Rules
Key rules about constants:
- A
constobject must be initialized (for class types, a default constructor still counts as initialization). constobjects cannot be modified after initialization.const≠ compile-time constant. Only constant expressions (e.g.,constexprorconstintegral initialized with a constant expression) can be used where a compile-time value is required.- Namespace-scope
constobjects have internal linkage by default. To share a constant across translation units, useextern constwith a single definition, or preferinline constexpr(C++17+).
Constants in Classes
const data members must be initialized by a default member initializer or in the constructor's member-initializer list.
Pointers and Const
Const with pointers can apply to the pointed-to value, the pointer itself, or both.
When to Use Constants
Use constants for values that should not change during program execution, such as:
- Mathematical constants (
PI,E) - Configuration values (
MAX_CONNECTIONS) - Conversion factors (
KM_PER_MILE) - Domain-specific fixed values