Const

Uses your system voice; voice and rate in settings.

Snapshot

≈ 14 min read

Names in other languages

No names in other languages are held for this entry yet.

Article bodies are English and are not machine-translated. A name in another language is not a translation of the article.

In some programming languages, 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, 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.

In some programming languages, 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, 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. void f(int& x); // ... const int i; f(i); because the argument to f must be a variable integer, but i 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 const 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). For simple non-pointer data types, applying the const qualifier is straightforward. It can go on either side of some types for historical reasons (for example, const char foo = 'a'; is equivalent to char const foo = 'a'; ). On some implementations, using const twice (for instance, const char const or char const const ) generates a warning but not an error. void foo(int* p, const int* cp, int* const pc, const int* const cpc) { *p = 0; // OK: modifies the pointed to data p = NULL; // OK: modifies the pointer *cp = 0; // Error! Cannot modify the pointed to data cp = NULL; // OK: modifies the pointer *pc = 0; // OK: modifies the pointed to data pc = NULL; // Error! Cannot modify the pointer *cpc = 0; // Error! Cannot modify the pointed to data cpc = NULL; // Error! Cannot modify the pointer } int* p; // *p is an int value const int* cp; // *cp is a constant int int* const pc; // pc is a constant int* const int* const cpc; // cpc is a constant pointer and points to a constant value const int* cp; // equivalent to int const* cp, const int* const cpc; // equivalent to int const* const cpc 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 const before what must be constant quickly introduces mismatches between what is intended to be written and what the compiler decides was written. Consider pointers to pointers: int** pp; // a pointer to a pointer to ints const int** cpp; // a pointer to a pointer to constant int value (not a pointer to a constant pointer to ints) int* const* pcp; // a pointer to a const pointer to int values (not a constant pointer to a pointer to ints) int** const ppc; // a constant pointer to pointers to ints (ppc, the identifier, being const makes no sense) const int** const cppc; // a constant pointer to pointers to constant int values Some choose to write the pointer symbol on the variable, reasoning that attaching it to the type is potentially confusing, as it strongly suggests a pointer "type" which is not necessarily the case in C. // two ways: int* a; // left-aligned asterisk int *a; // right-aligned asterisk int* a, b; // confusing (a is a pointer to an int but b is merely an int) int *a, b; // a is a pointer to an int and b is an int int* a, *b; // ugly (a and b are both pointers to ints, but this is an awkward way to write) int *a, *b; Note that in C#, right-alignment of the asterisk is illegal. int *a, *b; // illegal in C# int* a, b; // declares two int* 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: int i = 22; const int& cr = i; const int& cr2 = i, cr3 = i; // confusing: // cr2 is a reference, but cr3 isn't: // cr3 is a constant int initialized with i's value // error: as references can't change anyway. int& const rc = myInt; // C++: int&& rref = int(5), value = 10; // confusing: rref is an rvalue reference, but value is a mere int. int &&rref = int(5), value = 10; 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. 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 const automatic 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. class Integer { private: int i; public: // note the const tag nodiscard int get() const noexcept { return i; } // Note the lack of "const" void set(int j) noexcept { i = j; } }; void foo(Integer& nonConstInteger, const Integer& constInteger) { int y = nonConstInteger.get(); // OK int x = constInteger.get(); // OK: get() is const nonConstInteger.set(10); // OK: nonConstInteger is modifiable constInteger.set(10); // Error! set() is a non-const method and constInteger is a const-qualified object } In the above code, the implicit " this " pointer to set() has the type " Integer* const "; whereas the " this " pointer to get() has type " Integer const* const ", indicating that the method cannot modify its object through the " this " pointer. Often the programmer will supply both a const and a non- const method with the same name (but possibly quite different uses) in a class to accommodate both types of callers. Consider: import std; using std::array; class IntegerArray { private: array data; public: nodiscard int& get(int i) noexcept { return data[i]; } nodiscard int const& get(int i) const noexcept { return data[i]; } }; void foo(IntegerArray& a, const IntegerArray& ca) { // Get a reference to an array element // and modify its referenced value. a.get(5) = 42; // OK! (Calls: int& IntegerArray::get(int)) ca.get(5) = 42; // Error! (Calls: int const& IntegerArray::get(int) const) } The const -ness of the calling object determines which version of IntegerArray::get() 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 " this " pointers have different types, allowing the compiler to choose the right one. (Returning a const reference to an int , instead of merely returning the int 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.) // Prototype for a function which we cannot change but which // we know does not modify the pointee passed in. void myLibFunc(int* p, int size); void callLibFunc(const int* p, int size) { myLibFunc(p, size); // Error! Drops const qualifier int* nonConstPtr = const_cast (p); // Strip qualifier myLibFunc(nonConstPtr, size); // OK } However, any attempt to modify an object that is itself declared const by means of a const cast results in undefined behavior according to the ISO C++ Standard. In the example above, if ptr references a global, local, or member variable declared as const , or an object allocated on the heap via new int const , the code is only correct if LibraryFunc really does not modify the value pointed to by ptr . 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 const or not, or whether the static duration variable is being declared const or not. There is a non-portable way to initialize a const variable that has static storage duration. By carefully constructing a typecast on the left hand side of a later assignment, a const variable can be written to, effectively stripping away the const attribute and 'initializing' it with non-constant elements like other const variables and such. Writing into a const variable this way may work as intended, but it causes undefined behavior and seriously contradicts const-correctness: constexpr size_t BUFFER_SIZE = 8 * 1024; const size_t userTextBufferSize; // initial value depends on const BUFFER_SIZE, can't be initialized here ... int setupUserTextBox(TextBox* defaultTextBoxType, Rectangle* defaultTextBoxLocation) { *(size_t*)&userTextBufferSize = BUFFER_SIZE - sizeof(TextBoxControls); // warning: might work, but not guaranteed by C ... } Another loophole applies both to C and C++. Specifically, the languages dictate that member pointers and references are "shallow" with respect to the const -ness of their owners – that is, a containing object that is const has all const members except that member pointees (and referees) are still mutable. To illustrate, consider this C++ code: struct MyStruct { int val; int* ptr; }; void foo(const MyStruct& s) { int i = 42; s.val = i; // Error: s is const, so val is a const int s.ptr = &i; // Error: s is const, so ptr is a const pointer to int *s.ptr = i; // OK: the data pointed to by ptr is always mutable, even though this is sometimes not desirable } Although the object s passed to foo() is constant, which makes all of its members constant, the pointee accessible through s.ptr is still modifiable, though this may not be desirable from the standpoint of const -correctness because s might solely own the pointee. For this reason, Meyers argues that the default for member pointers and references should be "deep" const -ness, which could be overridden by a mutable 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 const -correct interface, but such classes either do not support the usual copy semantics from a const object (implying that the containing class cannot be copied by the usual semantics either) or allow other loopholes by permitting the stripping of const -ness through inadvertent or intentional copying. Finally, several functions in the C standard library violate const-correctness before C23, as they accept a const pointer to a character string and return a non- const pointer to a part of the same string. strstr and strchr 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 " const " version and a "non- const " version. char* strchr(char* s, int c); The strchr function does not modify the input string, but the return value is often used by the caller to modify the string, such as: if (p = strchr(q, '/')) { *p = ' '; } Thus on the one hand the input string can be const (since it is not modified by the function), and if the input string is const 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 const if the original string was not const , 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 const -qualified type as the input: char* strchr(char* s, int c); const char* strchr(const char* s, int c); These can in turn be defined by a template: template T* strchr(T* s, int c) { ... } In D this is handled via the inout keyword, which acts as a wildcard for const, immutable, or unqualified (variable), yielding: inout(char)* strchr(inout(char)* s, int c); 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: char* strchr(const char* s, int c); 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 the _Generic facility of the language: the identifiers of strchr and the other functions affected by the issue have been turned into macros that expand a call to an appropriate function which will return a const pointer if one was passed to them and an unqualified pointer if an unqualified pointer was passed to them. int[] foo = new int[5]; // foo is mutable. const int[] bar = foo; // bar is a const view of mutable data. immutable int[] baz = foo; // Error: all views of immutable data must be immutable. immutable int[] nums = new immutable(int)[5]; // No mutable reference to nums may be created. const int[] constNums = nums; // Works. immutable is implicitly convertible to const. int[] mutableNums = nums; // Error: Cannot create a mutable view of immutable data. Example of transitive or deep const in D class LinkedList { int value; LinkedList next; } immutable LinkedList ll = new immutable(LinkedList); ll.next.value = 5; // Won't compile. ll.next is of type immutable(LinkedList). // ll.next.value is of type immutable(int).

Text derived from https://en.wikipedia.org/w/index.php?oldid=1378707994 under CC BY-SA 4.0; modifications have been made.