The Keyword const
Declaring an entity to be const tells the compiler to make it "read-only." const can be applied usefully in a large number of programming situations, as we will soon see.
Because it cannot be assigned to, a const object must be properly initialized. For example:
const int x = 33; const int v[] = {3, 6, x, 2 * x};
Working with the declarations above:
++x ; // error v[2] = 44; // error
Compilers can take advantage of an object being read-only in various ways. For integers and some simple types, no storage needs to be allocated for a const unless its address is taken. Therefore, most optimizing compilers try to store them in static memory.
It is good programming style to use const entities instead of embedding constant expressions (sometimes called "magic numbers") in your code. This will gain you flexibility later when you need to change the values and, in general, it will improve the maintainability of your programs. For example, instead of 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) { ... }
In some C/C++ programs, you might see constants defined with 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 constant expressions. Generally const expressions are preferred to macros for defining constant values in C++ programs. |