Const (computer programming): Difference between revisions

Content deleted Content added
+mutable keyword. might deserve its own article, but for now its here
Explanation of C/C++ syntax. This might be better at wikibooks, but at least now it's somewhere.
Line 4:
 
In C++, a member variable declared with the ''mutable'' keyword can be modified when the method or even the entire class is const. This can be used to maintain internal data that needs to change even in const objects, such as in [[Reference counting|reference counting]] and [[cache|caching]].
 
==C/C++ Syntax==
For simple types the C++ keyword <code>const</code> can be put next to the type, but the syntax can become complex when types include pointers or references.
 
For simple types, the <code>const</code> can go on either side of the type. (Apparently the ambiguity is for historical reasons, to some extent).
const char foo;
is equivalent to
char const foo;
Both are <code>char</code>s with constant value (and, as a result, the above two lines don't compile because foo is const yet uninitialized). (In g++, at least, "<code>const char const foo</code>" gives a "<code>duplicate 'const'</code>" warning.)
 
'''If you have a pointer type, everything before the star is what's pointed to.''' So
const char * foo;
is equivalent to
char const * foo;
Both are pointers to a <code>const char</code> or an array of <code>const char</code>s. The same goes for references.
 
With anything more complex than that, it probably means a higher-level structure is in order. Any <code>*</code>s or <code>&</code>s in a type apply to everything on their left. So
const char * & const foo;
is a constant reference to a pointer to an array of constant characters, and
char * * const * foo;
is a pointer to a constant pointer to a pointer to a character array.
 
{{compu-lang-stub}}