Const (computer programming): Difference between revisions

Content deleted Content added
top: word choice
change C2X to C23
Line 266:
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 [[C2xC23 (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>[[strstr]]</code> and <code>[[strchr]]</code> are among these functions.
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 309:
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 [[C2xC23 (C standard revision)|C23]], this problem is solved with the use of generic functions. <code>strchr</code> and the other functions affected by the issue 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 ==