The
concept of
constant
(expressed by the
const
keyword) was created to allow the programmer to draw a line between what
changes and what doesn’t.
This
provides safety and control in a C++ programming project. Since its origin, it
has taken on a number of different purposes. In the meantime it trickled back
into the C language where its meaning was changed. All this can seem a bit
confusing at first, and in this chapter you’ll learn when, why, and how
to use the
const
keyword. At the end there’s a discussion of
volatile,
which is a near cousin to
const
(because they both concern change) and has identical syntax.
The
first motivation for
const
seems to have been to eliminate the use of preprocessor
#defines
for value substitution. It has since been put to use for pointers, function
arguments, and return types, and class objects and member functions. All of
these have slightly different but conceptually compatible meanings and will be
looked at in separate sections.