[ 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 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}; // a const array
Working with the declarations above:
++x ; // error v[2] = 44; // error
For integers and some other simple types, no storage needs to be allocated for a const unless its address is taken. Most optimizing compilers try to store such const objects 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. In general, isolating constants will improve 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 | |
|---|---|
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 constant expressions. Generally |
| Generated: $Date: 2009-09-08 12:15:32 -0400 (Tue, 08 Sep 2009) $ | © 2009 Alan Ezust and Paul Ezust. |