The const
keyword indicates a variable that is to be constant.
Two primary applications:
- to indicate a constant “parameter”
- to indicate which function arguments might be modified
int foo( const double *input_variable, double *output_variable )
Most modern code is written to be const-correct.
Casting
non-const
to const
is always permitted:
the other way is always a problem.
Confusions
Note that it is easy (in C) and possible in C++ to override const-ness. It should be taken as a guarantee, and a contract.
One hears the objection to const
that because it can be
overridden, it is useless.
That is a confusion of the purpose of the const paradigm. It’s not about certainty or security. It’s about responsibility. By calling a function that takes a non-const pointer argument, you are giving it the responsibility of changing the data.