Const (computer programming): Difference between revisions

Content deleted Content added
Ophura (talk | contribs)
m I think the edits I made help reading in a natural way, such that "that indicates that" becoming "which indicates that" and "on each" to "for each"...
fixes (mainly punc)
Line 2:
{{use dmy dates|date=December 2022|cs1-dates=y}}
{{lowercase title}}
In some [[programming language]]s, '''const''' is a [[type qualifier]] (a [[Keyword (computer programming)|keyword]] applied to a [[data type]]), whichthat indicates that the data is read-only. While this can be used to declare [[Constant (computer programming)|constants]], {{mono|const}} in the [[List of C-family programming languages|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 [[Pointer (computer programming)|pointers]], references, [[composite data type]]s, and [[type-checking]]. In other languages, the data is not in a single [[memory ___location]], but copied at [[compile time]] for each use.<ref>{{Cite web |title=Constant items - The Rust Reference |url=https://doc.rust-lang.org/reference/items/constant-items.html |access-date=2022-06-22 |website=doc.rust-lang.org}}</ref> Languages which use it include [[C (programming language)|C]], [[C++]], [[D (programming language)|D]], [[JavaScript]], [[Julia (programming language)|Julia]], and [[Rust (programming language)|Rust]].
 
== Introduction ==
Line 28:
 
== Syntax ==
In C, C++, and D, all data types, including those defined by the user, can be declared <code>const</code>, and const-correctness dictates that all variables or objects should be declared as such unless they need to be modified. Such proactive use of <code>const</code> makes values "easier to understand, track, and reason about,",<ref>[[Herb Sutter]] and [[Andrei Alexandrescu]] (2005). ''C++ Coding Standards''. p. 30. Boston: Addison Wesley. {{ISBN|0-321-11358-6}}</ref> 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.<ref>{{cite web|url=https://lkml.org/lkml/2013/1/12/139 |title=Why is the kfree() argument const? |publisher=lkml.org |date=2013-01-12}}</ref>
 
=== Simple data types ===
Line 57:
 
==== C convention ====
Following usual C convention for declarations, declaration follows use, and the <code>*</code> in a pointer is written on the pointer, indicating [[dereferencing]]. For example, in the declaration <code>int *ptr</code>, the dereferenced form <code>*ptr</code> is an <code>int</code>, while the reference form <code>ptr</code> is a pointer to an <code>int</code>. Thus <code>const</code> modifies the ''name'' to its right. The C++ convention is instead to associate the <code>*</code> with the type, as in <code>int* ptr,</code>, and read the <code>const</code> as modifying the ''type'' to the left. <code>int const * ptrToConst</code> can thus be read as "<code>*ptrToConst</code> is a <code>int const</code>" (the value is constant), or "<code>ptrToConst</code> is a <code>int const *</code>" (the pointer is a pointer to a constant integer). Thus:
<syntaxhighlight lang=c>
int *ptr; // *ptr is an int value
Line 100:
 
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 <code>const</code> ''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:
 
<syntaxhighlight lang=cpp>
int **ptr; // a pointer to a pointer to ints
Line 155 ⟶ 154:
 
This example illustrates:
 
<syntaxhighlight lang="cpp">
class C
Line 180 ⟶ 178:
 
Often the programmer will supply both a <code>const</code> and a non-<code>const</code> method with the same name (but possibly quite different uses) in a class to accommodate both types of callers. Consider:
 
<syntaxhighlight lang="cpp">
class MyArray
Line 227 ⟶ 224:
 
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 <code>const</code> or not, or whether the static duration variable is being declared <code>const</code> or not. There is a non-portable way to initialize a <code>const</code> variable that has static storage duration. By carefully constructing a typecast on the left hand side of a later assignment, a <code>const</code> variable can be written to, effectively stripping away the <code>const</code> attribute and 'initializing' it with non-constant elements like other <code>const</code> variables and such. Writing into a <code>const</code> variable this way may work as intended, but it causes undefined behavior and seriously contradicts const-correctness:
 
<syntaxhighlight lang="cpp">
size_t const bufferSize = 8*1024;
Line 241 ⟶ 237:
</syntaxhighlight>
 
Another loophole<ref>[[Scott Meyers]] (2005). ''Effective C++, Third Edition''. pp. 21-2321–23. Boston: Addison Wesley. {{ISBN|978-0-321-33487-9}}</ref> applies both to C and C++. Specifically, the languages dictate that member pointers and references are "shallow" with respect to the <code>const</code>-ness of their owners that is, a containing object that is <code>const</code> has all <code>const</code> members except that member pointees (and referees) are still mutable. To illustrate, consider this C++ code:
 
<syntaxhighlight lang="cpp">
Line 340 ⟶ 336:
 
== History ==
<code>const</code> was introduced by [[Bjarne Stroustrup]] in [[C with Classes]], the predecessor to [[C++]], in 1981, and was originally called <code>readonly</code>.<ref>[[Bjarne Stroustrup]], "Extensions of the C Language Type Concept.", Bell Labs internal Technical Memorandum, January 5, 1981.</ref><ref name="siblings">[http://www.stroustrup.com/sibling_rivalry.pdf Sibling Rivalry: C and C++], [[Bjarne Stroustrup]], 2002, p. 5</ref> As to motivation, Stroustrup writes:<ref name="siblings" />
: "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 <code>inline</code> keyword. Constant pointers, and the <code>* const</code> notation, were suggested by Dennis Ritchie and so adopted.<ref name="siblings" />
 
Line 356 ⟶ 352:
[[Nim (programming language)|Nim]] has a <code>const</code> 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.<ref>[http://nim-lang.org/docs/manual.html#statements-and-expressions-const-section Nim Manual: Const section]</ref> In C#, only C# built-in types can be declared as <code>const</code>; user-defined types, including classes, structs, and arrays, cannot be <code>const</code>.<ref>[https://msdn.microsoft.com/en-us/library/e6w8fe1b.aspx const (C# Reference)]</ref>
 
Java does not have <code>const</code> – it instead has <code>final</code>, 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 <code>const</code> 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). It is thought that the reservation of the keyword occurred to allow for an extension of the Java language to include C++-style <code>const</code> methods and pointer to <code>const</code> type.{{Citation needed|date=February 2011}} An enhancement request ticket for implementing <code>const</code> 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.<ref>{{cite web|url=http://bugs.java.com/view_bug.do?bug_id=4211070 |title=Bug ID: JDK-4211070 Java should support const parameters (like C++) for code {{sic|nolink=y|mai|ntainence}}|publisher=Bugs.sun.com |date= |accessdate=2014-11-04}}<!-- was previously at:
Line 374 ⟶ 370:
 
== Notes ==
{{Notelistnotelist}}
 
== References ==
{{Reflistreflist}}
 
== External links ==