Constants in programming are definitions whose value is fixed throughout a program's execution. Literals in most languages are constants, for example. In referentially transparent programming styles, all definitions are constant. A const-qualified data storage area (object, field, variable, parameter) is one that "never changes", thus allowing extra code generator optimizations and additional static checking of program correctness.
In computer science, const-correctness is the form of program correctness that deals with the proper declaration of objects as mutable or immutable. The term is mostly used in a C or C++ context, and takes its name from the const
keyword in those languages.
The idea of const
-ness does not imply that the variable as it is stored in the computer's memory is unwriteable. Rather, const
-ness is a compile-time construct that indicates what a programmer may do, not necessarily what they can do.
In addition, a method can be declared as const
. In this case, the this
pointer inside such a method is of const ThisClass* const
type rather than of ThisClass* const
type. This means that non-const
methods for this object cannot be called from inside such a method, nor can member variables be modified. In C++, a member variable can be declared as mutable
, indicating that this restriction does not apply to it. In some cases, this can be useful, for example with caching, reference counting, and data synchronization. In these cases, the logical meaning (state) of the object is unchanged, but the object is not physically constant since its bitwise representation may change.
The C++11 standard adds additional notes on the meaning of const
when used in the Standard Library with respect to thread access and possible modifications of those const
objects.
More about const-correctness here.