Content deleted Content added
→C++ convention: this is the c++ section of the article |
m Disambiguating links to Object-orientation (link changed to Object-oriented programming) using DisamAssist. |
||
(47 intermediate revisions by 30 users not shown) | |||
Line 1:
{{short description|Type qualifier denoting the data as being read-only}}
{{use dmy dates|date=December 2022|cs1-dates=y}}
{{lowercase title}}
In
== Introduction ==
Line 8 ⟶ 10:
This has two subtle results. Firstly, <code>const</code> can be applied to parts of a more complex type – for example, <code>int const * const x;</code> declares a constant pointer to a constant integer, while <code>int const * x;</code> declares a variable pointer to a constant integer, and <code>int * const x;</code> declares a constant pointer to a variable integer. Secondly, because <code>const</code> is part of the type, it must match as part of type-checking. For example, the following code is invalid:
<syntaxhighlight lang="cpp">
void f(int& x);
// ...
Line 20 ⟶ 22:
== Distinction from constants ==
While a constant does not change its value while the program is running, an object declared <code>const</code> 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 <code>const</code> and <code>[[volatile (computer programming)|volatile]]</code>. The content of these registers may change without the program doing anything (<code>volatile</code>) but
== Other uses ==
Line 26 ⟶ 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
=== Simple data types ===
Line 32 ⟶ 34:
=== Pointers and references ===
For pointer and reference types, the meaning of <code>const</code> is more complicated – either the pointer itself, or the value being pointed to, or both, can be <code>const</code>. Further, the syntax can be confusing. A pointer can be declared as a <code>const</code> pointer to writable value, or a writable pointer to a <code>const</code> value, or <code>const</code> pointer to <code>const</code> value. {{anchor|Pointee|Cray pointer|Cray character pointer}}A <code>const</code> 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]]''<!-- Might be better described somewhere else, hence circular link with possibilities for now. If you point or move this elsewhere, please also take care of the incoming redirects to "Pointee" and "Cray pointer". -->).<ref>{{cite book |title=The GNU Fortran Compiler |chapter=5.1. Extensions implemented in GNU Fortran: 5.1.16 Cray pointers |date=2006 |url=https://gcc.gnu.org/onlinedocs/gfortran/Cray-pointers.html#Cray-pointers |access-date=2022-12-21 |url-status=live |archive-url=https://web.archive.org/web/20221221175054/https://gcc.gnu.org/onlinedocs/gfortran/Cray-pointers.html#Cray-pointers |archive-date=2022-12-21}}</ref><ref>{{cite web |title=Cray Fortran Pointers vs. Fortran 90 Pointers and Porting from the Cray C90 to the SGI Origin2000 |author-first1=Mark R. |author-last1=Fahey |author-first2=Dan |author-last2=Nagle |publisher=US Army Corps of Engineers Waterways Experiment Station, Major Shared Resource Center |publication-place=Vicksburg, Massachusetts, USA |date=1999-04-19 |url=https://fs.hlrs.de/projects/par/mooc/cray-pointers.pdf |access-date=2022-12-23 |url-status=live |archive-url=https://web.archive.org/web/20221223105738/https://fs.hlrs.de/projects/par/mooc/cray-pointers.pdf |archive-date=2022-12-23}} (8 pages)</ref><ref>{{cite web |title=Appendix C: Fortran 90 Features and Differences > Features > Cray Pointers |work=Fortran User's Guide |date=2010 |publisher=[[Oracle Corporation]] |url=https://docs.oracle.com/cd/E19957-01/805-4941/z40000a54ba7/index.html |access-date=2022-12-23 |url-status=live |archive-url=https://web.archive.org/web/20210921171349/https://docs.oracle.com/cd/E19957-01/805-4941/z40000a54ba7/index.html |archive-date=2021-09-21}}</ref><ref>{{cite web |title=Appendix C: Fortran 90 Features and Differences > Features > Cray Character Pointers |work=Fortran User's Guide |date=2010 |publisher=[[Oracle Corporation]] |url=https://docs.oracle.com/cd/E19957-01/805-4941/z40000a5510b/index.html |access-date=2022-12-23 |url-status=live |archive-url=https://web.archive.org/web/20221223112633/https://docs.oracle.com/cd/E19957-01/805-4941/z40000a5510b/index.html |archive-date=2022-12-23}}</ref><ref>{{cite book |title=Fortran Language Reference Manual, Volume 1 |volume=1 |id=Document Number: 007-3692-004 |chapter=Chapter 4. Data Types |date=1999 |orig-date=1993 |publisher=[[Silicon Graphics, Inc.]] |url=https://techpubs.jurassic.nl/manuals/0630/developer/Ftn_LRM_V1/sgi_html/ch04.html |access-date=2022-12-23 |url-status=live |archive-url=https://web.archive.org/web/20221223110605/https://techpubs.jurassic.nl/manuals/0630/developer/Ftn_LRM_V1/sgi_html/ch04.html |archive-date=2022-12-23}} (NB. Derived from "FORTRAN 90 HANDBOOK" (1992, [[McGraw-Hill, Inc.]]) by Walter S. Brainerd, Jeanne C. Adams, Jeanne T. Martin, Brian T. Smith, and Jerrold L. Wagener.)</ref> Reference variables in C++ are an alternate syntax for <code>const</code> pointers. A pointer to a <code>const</code> 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 <code>const</code> pointer to a <code>const</code> object can also be declared and can neither be used to modify the
<syntaxhighlight lang="c">
void Foo( int * ptr,
int const * ptrToConst,
Line 40 ⟶ 42:
int const * const constPtrToConst )
{
*ptr = 0; // OK: modifies the
ptr = NULL; // OK: modifies the pointer
*ptrToConst = 0; // Error! Cannot modify the
ptrToConst = NULL; // OK: modifies the pointer
*constPtr = 0; // OK: modifies the
constPtr = NULL; // Error! Cannot modify the pointer
*constPtrToConst = 0; // Error! Cannot modify the
constPtrToConst = NULL; // Error! Cannot modify the pointer
}
Line 55 ⟶ 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
<syntaxhighlight lang="c">
int *ptr; // *ptr is an int value
int const *ptrToConst; // *ptrToConst is a constant (int: integer value)
int * const constPtr; // constPtr is a constant (int *: integer pointer)
int const * const constPtrToConst; // constPtrToConst is a constant
//
</syntaxhighlight>
==== 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
A more generic rule that helps you understand complex declarations and definitions works like this:
Line 98 ⟶ 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">▼
▲<syntaxhighlight lang=cpp>
int **ptr; // a pointer to a pointer to ints
int const **ptr // a pointer to a pointer to constant int value
Line 147 ⟶ 148:
=== 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 <code>const</code> if they don't modify the object's data members.
Applying the <code>const</code> qualifier to instance methods thus is an essential feature for const-correctness, and is not available in many other [[Object-oriented programming|object-oriented]] languages such as [[Java (programming language)|Java]] and [[C Sharp (programming language)|C#]] or in [[Microsoft]]'s [[C++/CLI]] or [[Managed Extensions for C++]].
While <code>const</code> methods can be called by <code>const</code> and non-<code>const</code> objects alike, non-<code>const</code> methods can only be invoked by non-<code>const</code> objects.
The <code>const</code> modifier on an instance method applies to the object pointed to by the "<code>[[this (computer science)|this]]</code>" pointer, which is an implicit argument passed to all instance methods.
Line 153 ⟶ 154:
This example illustrates:
<syntaxhighlight lang="cpp">
class C
Line 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 225 ⟶ 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
size_t const
...
Line 239 ⟶ 237:
</syntaxhighlight>
Another loophole<ref>[[Scott Meyers]] (2005). ''Effective C++, Third Edition''. pp.
<syntaxhighlight lang="cpp">
Line 264 ⟶ 262:
The latter loophole can be closed by using a class to hide the pointer behind a <code>const</code>-correct interface, but such classes either do not support the usual copy semantics from a <code>const</code> object (implying that the containing class cannot be copied by the usual semantics either) or allow other loopholes by permitting the stripping of <code>const</code>-ness through inadvertent or intentional copying.
Finally, several functions in the [[C standard library]] violate const-correctness before [[C23 (C standard revision)|C23]], as they accept a <code>const</code> pointer to a character string and return a non-<code>const</code> pointer to a part of the same string. <code>[[
Some implementations of the C++ standard library, such as Microsoft's<ref>{{cite web|url=https://msdn.microsoft.com/en-us/library/b34ccac3.aspx |title= strchr, wcschr, _mbschr (CRT) |publisher= Msdn.microsoft.com |date= |accessdate= 2017-11-23 }}</ref> try to close this loophole by providing two [[function overloading|overloaded]] versions of some functions: a "<code>const</code>" version and a "non-<code>const</code>" version.
Line 275 ⟶ 273:
This problem arises even for simple functions in the C standard library, notably <code>strchr</code>; this observation is credited by Ritchie to Tom Plum in the mid 1980s.<ref>{{Cite web | url=http://www.lysator.liu.se/c/dmr-on-noalias.html |title = Dennis Ritchie: Why I do not like X3J11 type qualifiers}}</ref> The <code>strchr</code> function locates a character in a string; formally, it returns a pointer to the first occurrence of the character <code>c</code> in the string <code>s</code>, and in classic C (K&R C) its prototype is:
<syntaxhighlight lang="c">
char *strchr(char *s, int c);
</syntaxhighlight>
The <code>strchr</code> function does not modify the input string, but the return value is often used by the caller to modify the string, such as:
<syntaxhighlight lang="c">
if (p = strchr(q, '/'))
*p = ' ';
Line 286 ⟶ 284:
In C++ this is done via [[function overloading]], typically implemented via a [[Template (C++)|template]], resulting in two functions, so that the return value has the same <code>const</code>-qualified type as the input:{{efn|Note that pointer declaration syntax conventions differ between C and C++: in C <code>char *s</code> is standard, while in C++ <code>char* s</code> is standard.}}
<syntaxhighlight lang="cpp">
char* strchr(char* s, int c);
char const* strchr(char const* s, int c);
</syntaxhighlight>
These can in turn be defined by a template:
<syntaxhighlight lang="cpp">
template <T>
T* strchr(T* s, int c) { ... }
Line 301 ⟶ 299:
</syntaxhighlight>
However, in C neither of these is possible{{efn|In
<syntaxhighlight lang=
char const* strchr_c(char const *s, int c);
#define strchr(X,Y) _Generic((X), \
char*: strchr_m, \
const char*: strchr_c \
)(X,Y)</syntaxhighlight>}} 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:
<syntaxhighlight lang="cpp">
char *strchr(char const *s, int c);
</syntaxhighlight>
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 (C standard revision)|C23]], this problem is solved with the use of the <code>_Generic</code> facility of the language: the identifiers of <code>strchr</code> 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 <code>const</code> pointer if one was passed to them and an unqualified pointer if an unqualified pointer was passed to them.<!-- The phrasing needs some work but keep in mind that the array elements cannot be volatile or restrict. --><ref name="N3020">{{cite web |title=WG14-N3020 : Qualifier-preserving standard library functions |url=https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3020.pdf |website=open-std.org |archive-url=https://web.archive.org/web/20221013190826/https://www.open-std.org/jtc1/sc22/WG14/www/docs/n3020.pdf |archive-date=October 13, 2022 |date=2022-06-13 |url-status=live}}</ref>
== D ==
In
The <code>const</code> keyword denotes a non-mutable view of mutable data.
Unlike C++ <code>const</code>, D <code>const</code> and <code>immutable</code> are "deep" or [[transitive relation|transitive]], and anything reachable through a <code>const</code> or <code>immutable</code> object is <code>const</code> or <code>immutable</code> respectively.
Line 336 ⟶ 343:
== 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
: "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" />
<code>const</code> was then adopted in C as part of standardization, and appears in [[ANSI C|C89]] (and subsequent versions) along with the other type qualifier, <code>volatile</code>.<ref>[[Dennis M. Ritchie]], "[http://cm.bell-labs.com/who/dmr/chist.html The Development of the C Language] {{webarchive |url=https://archive.
'Volatile', in particular, is a frill for esoteric applications, and much better expressed by other means. Its chief virtue is that nearly everyone can forget about it. 'Const' is simultaneously more useful and more obtrusive; you can't avoid learning about it, because of its presence in the library interface. Nevertheless, I don't argue for the extirpation of qualifiers, if only because it is too late."</ref>
Line 348 ⟶ 355:
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 <code>const</code> keyword. Typically this is only used for constants (constant objects).
[[C Sharp (programming language)|C#]] has a <code>const</code> keyword, but with radically different and simpler semantics: it means a compile-time constant, and is not part of the type.
[[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 (programming language)|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
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).
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4211070
2013-08-18
Line 370 ⟶ 377:
== Notes ==
{{
== References ==
{{
== External links ==
|