Content deleted Content added
m →strchr problem: wording |
m Disambiguating links to Object-orientation (link changed to Object-oriented programming) using DisamAssist. |
||
(5 intermediate revisions by 4 users not shown) | |||
Line 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 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 apointee{{typo help inline|reason=similar to appointee|date=June 2025}} nor be reassigned to point to another object. The following code illustrates these subtleties:
<syntaxhighlight lang="c">
void Foo( int * ptr,
int const * ptrToConst,
Line 58:
==== 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
int const *ptrToConst; // *ptrToConst is a constant (int: integer 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
int const **ptr // a pointer to a pointer to constant int value
Line 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 225:
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 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 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 299:
</syntaxhighlight>
However, in C neither of these is possible{{efn|In C11 and later <code>_Generic</code> could have been used to implement a const-correct <code>strchr</code>.
<syntaxhighlight lang="c">char* strchr_m(char *s, int c);
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
<syntaxhighlight lang="cpp">
char *strchr(char const *s, int c);
</syntaxhighlight>
Line 312:
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
== 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 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'', 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). The keyword was included as a means for Java compilers to detect and warn about the incorrect usage of C++ keywords.<ref>{{Cite web |url=https://docs.oracle.com/javase/specs/jls/se6/html/lexical.html#3.9 |title=Java Language Specification Third Edition |last=Gosling |first=James |last2=Joy |first2=Bill |last3=Steele |first3=Guy}}</ref> 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:
|