[ fromfile: const-intro.xml id: const-intro ]
Declaring an entity to be
const
tells the compiler to make it "read-only."
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.
use const
entities instead of embedding numeric literals (sometimes called "magic numbers") in your code.
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 const expressions. Generally |
Generated: 2012-03-02 | © 2012 Alan Ezust and Paul Ezust. |