Constants
In old (pre-Standard) C, if you wanted to
make a constant, you had to use the
preprocessor:
#define PI 3.14159
Everywhere you used PI, the value
3.14159 was substituted by the preprocessor (you can still use this method in C
and C++).
When you use the preprocessor to create
constants, you place control of those constants outside the scope of the
compiler. No type checking is performed on the name
PI and you can’t take the address of PI (so you can’t
pass a pointer or a reference to
PI). PI cannot be a variable of a user-defined type. The meaning
of PI lasts from the point it is defined to the end of the file; the
preprocessor doesn’t recognize scoping.
C++ introduces the concept of a named
constant that is just like a
variable, except that its value cannot be changed. The modifier
const tells the compiler
that a name represents a constant. Any data type, built-in or user-defined, may
be defined as const. If you define something as const and then
attempt to modify it, the compiler will generate an error.
You must specify the type of a
const, like this:
const int x = 10;
In Standard C and C++, you can use a
named constant in an argument list, even if the argument it fills is a pointer
or a reference (i.e., you can take the address of a const). A
const has a scope, just like a regular variable, so you can
“hide” a const inside a function and be sure that the name
will not affect the rest of the program.
The const was taken from C++ and
incorporated into Standard C, albeit quite differently. In C, the compiler
treats a const just like a variable that has a special tag attached that
says “Don’t change me.” When you define a const in C,
the compiler creates storage for it, so if you define more than one const
with the same name in two different files (or put the definition in a header
file), the linker will generate error messages about conflicts. The intended use
of const in C is quite different from its intended use in C++ (in short,
it’s nicer in C++).