Topic summary

Const

Const

Extracted from the Wikipedia article Const (computer programming).

Parameters and variables

const can be declared both on function parameters and on variables (static or automatic, including global or local). The interpretation varies between uses. A const static variable (global variable or static local variable) is a constant, and may be used for data like mathematical constants, such as const double PI = 3.14159 – realistically longer, or overall compile-time parameters. A constautomatic variable (non-static local variable) means that single assignment is happening, though a different value may be used each time, such as const int x_squared = x * x. A const parameter in pass-by-reference means that the referenced value is not modified – it is part of the contract – while a const parameter in pass-by-value (or the pointer itself, in pass-by-reference) does not add anything to the interface (as the value has been copied), but indicates that internally, the function does not modify the local copy of the parameter (it is a single assignment). For this reason, some favor using const in parameters only for pass-by-reference, where it changes the contract, but not for pass-by-value, where it exposes the implementation.