Const (computer programming)

This is an old revision of this page, as edited by BenFrantzDale (talk | contribs) at 03:16, 11 May 2005 (Explanation of C/C++ syntax. This might be better at wikibooks, but at least now it's somewhere.). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

Const correctness is a programming language feature, its most famous implementor being C++. In languages supporting this feature, variables can be said to be 'const'. When a const object is referenced, only the methods declared as const may be called. This allows programmers to formalise a specific design contract: they can promise at compile-time that a parameter of a function cannot be modified destructively.

Of course, const methods can only call other const methods, and cannot assign member variables.

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 and caching.

C/C++ Syntax

For simple types the C++ keyword const can be put next to the type, but the syntax can become complex when types include pointers or references.

For simple types, the const 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 chars with constant value (and, as a result, the above two lines don't compile because foo is const yet uninitialized). (In g++, at least, "const char const foo" gives a "duplicate 'const'" 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 const char or an array of const chars. The same goes for references.

With anything more complex than that, it probably means a higher-level structure is in order. Any *s or &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.