1.14. The Keyword const

[ fromfile: const-intro.xml id: const-intro ]

Declaring an entity to be const tells the compiler to make it "read-only." const can be used in many contexts, as you will soon see.

Because it cannot be assigned to, a const object must be properly initialized when it is first declared. For example:

   const int x = 33;
   const int v[] = {3, 6, x, 2 * x};   // a const array

Working with the preceding declarations:

 ++x ;           // error
 v[2] = 44;      // error

No storage needs to be allocated for a const initialized with an int or some other simple type unless its address is taken. More generally, if the initializer for a const is a constant expression that can be evaluated at compile time, and the compiler knows every use of it, it might not be necessary to allocate any space for it.

It is good programming style to use const entities instead of embedding numeric literals (sometimes called "magic numbers") in your code. This cann gain you flexibility later when you need to change the values. In general, isolating constants improves the maintainability of your programs. For example, instead of writing something like this:

for(i = 0; i < 327; ++i) {
   ...
}

use something like this:

// const declaration section of your code
const int SIZE = 327;
...
for(i = 0; i < SIZE; ++i) {
    ...
}

[Note] Note

In some C/C++ programs, you might see constants defined as preprocessor macros like this:

#define STRSIZE 80
[...]
char str[STRSIZE];

Preprocessor macros get replaced before the compiler sees them. Using macros instead of constants means that the compiler cannot perform the same level of type checking as it can with proper const expressions. Generally const expressions are preferred to macros for defining constant values in C++ programs. Other uses of the preprocessor can be found in Section C.2.