Const (computer programming)

This is an old revision of this page, as edited by BenFrantzDale (talk | contribs) at 03:33, 11 May 2005 (cleanup). 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 that allows the programmer to indicate when an object can and cannot change. This can be used to improve encapsulation, correctness, and even performance. The best known language with this feature is C++. In languages supporting this feature, variables can be declared as 'const'. When a const object is used, the compiler will do its best to prevent the object from being changed. This allows programmers to formalise a simple form of design contract.

A class method can be declared as const, indicating that calling that method does not change the object. Const methods can only call other const methods, but cannot assign member variables. (In C++, a member variable can be declared as mutable, indicating that a const method can change its value. This can be used for caching and reference counting, where the meaning of the object is unchanged, but the object is not bitwise const.)

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.