Const (computer programming)

In some programming languages, const is a type qualifier (a keyword applied to a data type) that indicates that the data is read-only. While this can be used to declare constants, const in the C family of languages differs from similar constructs in other languages in that it is part of the type, and thus has complicated behavior when combined with pointers, references, composite data types, and type-checking. In other languages, the data is not in a single memory location, but copied at compile time for each use. Languages which use it include C, C++, D, JavaScript, Julia, and Rust.

Introduction
When applied in an object declaration, it indicates that the object is a constant: its value may not be changed, unlike a variable. This basic use – to declare constants – has parallels in many other languages.

However, unlike in other languages, in the C family of languages the  is part of the type, not part of the object. For example, in C, int const x = 1; declares an object  of   type – the   is part of the type, as if it were parsed "(int const) x" – while in Ada, X : constant INTEGER := 1_ declares a constant (a kind of object)   of   type: the   is part of the object, but not part of the type.

This has two subtle results. Firstly,  can be applied to parts of a more complex type – for example,   declares a constant pointer to a constant integer, while   declares a variable pointer to a constant integer, and   declares a constant pointer to a variable integer. Secondly, because  is part of the type, it must match as part of type-checking. For example, the following code is invalid: because the argument to  must be a variable integer, but   is a constant integer. This matching is a form of program correctness, and is known as const-correctness. This allows a form of programming by contract, where functions specify as part of their type signature whether they modify their arguments or not, and whether their return value is modifiable or not. This type-checking is primarily of interest in pointers and references – not basic value types like integers – but also for composite data types or templated types such as containers. It is concealed by the fact that the  can often be omitted, due to type coercion (implicit type conversion) and C being call-by-value (C++ and D are either call-by-value or call-by-reference).

Consequences
The idea of const-ness does not imply that the variable as it is stored in computer memory is unwritable. Rather, -ness is a compile-time construct that indicates what a programmer should do, not necessarily what they can do. Note, however, that in the case of predefined data (such as  string literals), C   is often unwritable.

Distinction from constants
While a constant does not change its value while the program is running, an object declared  may indeed change its value while the program is running. A common example are read only registers within embedded systems like the current state of a digital input. The data registers for digital inputs are often declared as  and. The content of these registers may change without the program doing anything but it would be ill-formed for the program to attempt write to them.

Other uses
In addition, a (non-static) member-function can be declared as. In this case, the  pointer inside such a function is of type   rather than merely of type. This means that non-const functions for this object cannot be called from inside such a function, nor can member variables be modified. In C++, a member variable can be declared as, 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.

Syntax
In C, C++, and D, all data types, including those defined by the user, can be declared, and const-correctness dictates that all variables or objects should be declared as such unless they need to be modified. Such proactive use of  makes values "easier to understand, track, and reason about", and it thus increases the readability and comprehensibility of code and makes working in teams and maintaining code simpler because it communicates information about a value's intended use. This can help the compiler as well as the developer when reasoning about code. It can also enable an optimizing compiler to generate more efficient code.

Simple data types
For simple non-pointer data types, applying the  qualifier is straightforward. It can go on either side of some types for historical reasons (for example,  is equivalent to  ). On some implementations, using  twice (for instance,   or  ) generates a warning but not an error.

Pointers and references
For pointer and reference types, the meaning of  is more complicated – either the pointer itself, or the value being pointed to, or both, can be. Further, the syntax can be confusing. A pointer can be declared as a  pointer to writable value, or a writable pointer to a   value, or   pointer to   value. A  pointer cannot be reassigned to point to a different object from the one it is initially assigned, but it can be used to modify the value that it points to (called the pointee). Reference variables in C++ are an alternate syntax for  pointers. A pointer to a  object, on the other hand, can be reassigned to point to another memory location (which should be an object of the same type or of a convertible type), but it cannot be used to modify the memory that it is pointing to. A  pointer to a   object can also be declared and can neither be used to modify the apointee nor be reassigned to point to another object. The following code illustrates these subtleties:

C convention
Following usual C convention for declarations, declaration follows use, and the  in a pointer is written on the pointer, indicating dereferencing. For example, in the declaration, the dereferenced form   is an  , while the reference form   is a pointer to an. Thus  modifies the name to its right. The C++ convention is instead to associate the  with the type, as in , and read the   as modifying the type to the left. can thus be read as " is a  " (the value is constant), or "  is a  " (the pointer is a pointer to a constant integer). Thus:

C++ convention
Following C++ convention of analyzing the type, not the value, a rule of thumb is to read the declaration from right to left. Thus, everything to the left of the star can be identified as the pointed type and everything to the right of the star are the pointer properties. For instance, in our example above,  can be read as a writable pointer that refers to a non-writable integer, and   can be read as a non-writable pointer that refers to a writable integer.

A more generic rule that helps you understand complex declarations and definitions works like this:
 * 1) find the identifier whose declaration you want to understand
 * 2) read as far as possible to the right (i.e., until the end of the declaration or to the next closing parenthesis, whichever comes first)
 * 3) back up to where you began, and read backwards to the left (i.e., until the beginning of the declaration or to the open-parenthesis matching the closing parenthesis found in the previous step)
 * 4) when you've reached the beginning of the declaration you're done. If not, continue at step 2, beyond the closing parenthesis that was matched last.

Here is an example:

When reading to the left, it is important that you read the elements from right to left. So an  becomes a pointer to a const int and not a const pointer to an int.

In some cases C/C++ allows the  keyword to be placed to the left of the type. Here are some examples:

Although C/C++ allows such definitions (which closely match the English language when reading the definitions from left to right), the compiler still reads the definitions according to the abovementioned procedure: from right to left. But putting  before what must be constant quickly introduces mismatches between what you intend to write and what the compiler decides you wrote. Consider pointers to pointers:

As a final note regarding pointer definitions: always write the pointer symbol (the *) as much as possible to the right. Attaching the pointer symbol to the type is tricky, as it strongly suggests a pointer type, which isn't the case. Here are some examples: Bjarne Stroustrup's FAQ recommends only declaring one variable per line if using the C++ convention, to avoid this issue.

The same considerations apply to defining references and rvalue references:

More complicated declarations are encountered when using multidimensional arrays and references (or pointers) to pointers. Although it is sometimes argued that such declarations are confusing and error-prone and that they therefore should be avoided or be replaced by higher-level structures, the procedure described at the top of this section can always be used without introducing ambiguities or confusion.

Parameters and variables
can be declared both on function parameters and on variables (static or automatic, including global or local). The interpretation varies between uses. A  static variable (global variable or static local variable) is a constant, and may be used for data like mathematical constants, such as   – realistically longer, or overall compile-time parameters. A  automatic variable (non-static local variable) means that single assignment is happening, though a different value may be used each time, such as. A  parameter in pass-by-reference means that the referenced value is not modified – it is part of the contract – while a   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  in parameters only for pass-by-reference, where it changes the contract, but not for pass-by-value, where it exposes the implementation.

Methods
In order to take advantage of the design by contract approach for user-defined types (structs and classes), which can have methods as well as member data, the programmer may tag instance methods as  if they don't modify the object's data members. Applying the  qualifier to instance methods thus is an essential feature for const-correctness, and is not available in many other object-oriented languages such as Java and C# or in Microsoft's C++/CLI or Managed Extensions for C++. While  methods can be called by   and non-  objects alike, non-  methods can only be invoked by non-  objects. The  modifier on an instance method applies to the object pointed to by the " " pointer, which is an implicit argument passed to all instance methods. Thus having  methods is a way to apply const-correctness to the implicit " " pointer argument just like other arguments.

This example illustrates:

In the above code, the implicit " " pointer to  has the type " "; whereas the " " pointer to   has type " ", indicating that the method cannot modify its object through the " " pointer.

Often the programmer will supply both a  and a non-  method with the same name (but possibly quite different uses) in a class to accommodate both types of callers. Consider:

The -ness of the calling object determines which version of   will be invoked and thus whether or not the caller is given a reference with which he can manipulate or only observe the private data in the object. The two methods technically have different signatures because their " " pointers have different types, allowing the compiler to choose the right one. (Returning a  reference to an , instead of merely returning the   by value, may be overkill in the second method, but the same technique can be used for arbitrary types, as in the Standard Template Library.)

Loopholes to const-correctness
There are several loopholes to pure const-correctness in C and C++. They exist primarily for compatibility with existing code.

The first, which applies only to C++, is the use of, which allows the programmer to strip the   qualifier, making any object modifiable. The necessity of stripping the qualifier arises when using existing code and libraries that cannot be modified but which are not const-correct. For instance, consider this code:

However, any attempt to modify an object that is itself declared  by means of a const cast results in undefined behavior according to the ISO C++ Standard. In the example above, if  references a global, local, or member variable declared as , or an object allocated on the heap via  , the code is only correct if   really does not modify the value pointed to by.

The C language has a need of a loophole because a certain situation exists. Variables with static storage duration are allowed to be defined with an initial value. However, the initializer can use only constants like string constants and other literals, and is not allowed to use non-constant elements like variable names, whether the initializer elements are declared  or not, or whether the static duration variable is being declared   or not. There is a non-portable way to initialize a  variable that has static storage duration. By carefully constructing a typecast on the left hand side of a later assignment, a  variable can be written to, effectively stripping away the   attribute and 'initializing' it with non-constant elements like other   variables and such. Writing into a  variable this way may work as intended, but it causes undefined behavior and seriously contradicts const-correctness:

Another loophole applies both to C and C++. Specifically, the languages dictate that member pointers and references are "shallow" with respect to the -ness of their owners – that is, a containing object that is   has all   members except that member pointees (and referees) are still mutable. To illustrate, consider this C++ code:

Although the object  passed to   is constant, which makes all of its members constant, the pointee accessible through   is still modifiable, though this may not be desirable from the standpoint of  -correctness because   might solely own the pointee. For this reason, Meyers argues that the default for member pointers and references should be "deep" -ness, which could be overridden by a   qualifier when the pointee is not owned by the container, but this strategy would create compatibility issues with existing code. Thus, for historical reasons, this loophole remains open in C and C++.

The latter loophole can be closed by using a class to hide the pointer behind a -correct interface, but such classes either do not support the usual copy semantics from a   object (implying that the containing class cannot be copied by the usual semantics either) or allow other loopholes by permitting the stripping of  -ness through inadvertent or intentional copying.

Finally, several functions in the C standard library violate const-correctness before C23, as they accept a  pointer to a character string and return a non-  pointer to a part of the same string. and  are among these functions. Some implementations of the C++ standard library, such as Microsoft's try to close this loophole by providing two overloaded versions of some functions: a " " version and a "non- " version.

Problems
The use of the type system to express constancy leads to various complexities and problems, and has accordingly been criticized and not adopted outside the narrow C family of C, C++, and D. Java and C#, which are heavily influenced by C and C++, both explicitly rejected -style type qualifiers, instead expressing constancy by keywords that apply to the identifier (  in Java,   and   in C#). Even within C and C++, the use of  varies significantly, with some projects and organizations using it consistently, and others avoiding it.

problem
The  type qualifier causes difficulties when the logic of a function is agnostic to whether its input is constant or not, but returns a value which should be of the same qualified type as an input. In other words, for these functions, if the input is constant (const-qualified), the return value should be as well, but if the input is variable (not -qualified), the return value should be as well. Because the type signature of these functions differs, it requires two functions (or potentially more, in case of multiple inputs) with the same logic – a form of generic programming.

This problem arises even for simple functions in the C standard library, notably ; this observation is credited by Ritchie to Tom Plum in the mid 1980s. The  function locates a character in a string; formally, it returns a pointer to the first occurrence of the character   in the string , and in classic C (K&amp;R C) its prototype is: The  function does not modify the input string, but the return value is often used by the caller to modify the string, such as: Thus on the one hand the input string can be  (since it is not modified by the function), and if the input string is   the return value should be as well – most simply because it might return exactly the input pointer, if the first character is a match – but on the other hand the return value should not be   if the original string was not , since the caller may wish to use the pointer to modify the original string.

In C++ this is done via function overloading, typically implemented via a template, resulting in two functions, so that the return value has the same -qualified type as the input: These can in turn be defined by a template:

In D this is handled via the  keyword, which acts as a wildcard for const, immutable, or unqualified (variable), yielding:

However, in C neither of these is possible since C does not have function overloading, and instead, this is handled by having a single function where the input is constant but the output is writable: This allows idiomatic C code but does strip the const qualifier if the input actually was const-qualified, violating type safety. This solution was proposed by Ritchie and subsequently adopted. This difference is one of the failures of compatibility of C and C++.

Since C23, this problem is solved with the use of generic functions. and the other functions affected by the issue will return a  pointer if one was passed to them and an unqualified pointer if an unqualified pointer was passed to them.

D
In Version 2 of the D programming language, two keywords relating to const exist. The  keyword denotes data that cannot be modified through any reference. The  keyword denotes a non-mutable view of mutable data. Unlike C++, D   and   are "deep" or transitive, and anything reachable through a   or   object is   or   respectively.

Example of const vs. immutable in D

Example of transitive or deep const in D

History
was introduced by Bjarne Stroustrup in C with Classes, the predecessor to C++, in 1981, and was originally called. As to motivation, Stroustrup writes:
 * "It served two functions: as a way of defining a symbolic constant that obeys scope and type rules (that is, without using a macro) and as a way of deeming an object in memory immutable."

The first use, as a scoped and typed alternative to macros, was analogously fulfilled for function-like macros via the  keyword. Constant pointers, and the  notation, were suggested by Dennis Ritchie and so adopted.

was then adopted in C as part of standardization, and appears in C89 (and subsequent versions) along with the other type qualifier,. A further qualifier,, was suggested at the December 1987 meeting of the X3J11 committee, but was rejected; its goal was ultimately fulfilled by the   keyword in C99. Ritchie was not very supportive of these additions, arguing that they did not "carry their weight", but ultimately did not argue for their removal from the standard.

D subsequently inherited  from C++, where it is known as a type constructor (not type qualifier) and added two further type constructors,   and , to handle related use cases.

Other languages
Other languages do not follow C/C++ in having constancy part of the type, though they often have superficially similar constructs and may use the  keyword. Typically this is only used for constants (constant objects).

C# has a  keyword, but with radically different and simpler semantics: it means a compile-time constant, and is not part of the type.

Nim has a  keyword similar to that of C#: it also declares a compile-time constant rather than forming part of the type. However, in Nim, a constant can be declared from any expression that can be evaluated at compile time. In C#, only C# built-in types can be declared as ; user-defined types, including classes, structs, and arrays, cannot be.

Java does not have  – it instead has , which can be applied to local "variable" declarations and applies to the identifier, not the type. It has a different object-oriented use for object members, which is the origin of the name.

The Java language specification regards  as a reserved keyword – i.e., one that cannot be used as variable identifier – but assigns no semantics to it: it is a reserved word (it cannot be used in identifiers) but not a keyword (it has no special meaning). The keyword was included as a means for Java compilers to detect and warn about the incorrect usage of C++ keywords. An enhancement request ticket for implementing  correctness exists in the Java Community Process, but was closed in 2005 on the basis that it was impossible to implement in a backwards-compatible fashion.

The contemporary Ada 83 independently had the notion of a constant object and a  keyword,  with input parameters and loop parameters being implicitly constant. Here the  is a property of the object, not of the type.

JavaScript has a  declaration that defines a block-scoped variable that cannot be reassigned nor redeclared. It defines a read-only reference to a variable that cannot be redefined, but in some situations the value of the variable itself may potentially change, such as if the variable refers to an object and a property of it is altered.