const
and #define
.
Before C had const
, we used to use #define
to define
constants, such as:
#define SUNDAY 0 #define MONDAY 1
It is a convention that macros should be entirely capitalized.
A macro, such as SUNDAY
and MONDAY
in our example, is
actually handled by the C pre-processor (CPP), and not a C compiler.
A CPP replaces all occurances of SUNDAY
with its definition,
0
, and all occurances of MONDAY
with its definition,
1
. By the time the C compiler gets the source code, there is
no SUNDAY
or MONDAY
left in the source code.
Because macros are expanded by the CPP, each source file that needs to
use SUNDAY
and MONDAY
should include the definitions.
That's why most of these definitions are placed in a header file.
After the introduction of const
, we can use the following
definitions instead:
const int sunday = 0; const int monday = 1;
Because this is a definition, it only needs to be done once in a source (not header) file. If another file needs to reference these constants, it can use the following declarations:
extern const int sunday, monday;
This declaration tells the compiler to find the actual definitions of
sunday
and monday
from another object file. Consequently,
there is no need to expose the actual definitions of sunday
and
monday
in a header file, which helps to protect information from
abuse.
There is one thing that const
cannot do. Consider the following
definitions in global scope:
const int n = 6; int someInts[n];
This is not permitted! This is because even though n
is designated
as a constant, it is still a variable (I know, I know, oxymoron).
If you want to use a symbol to represent the size of a global array, you
still need to use macros. Note that the same definitions in a local scope
works, even if n
is not const
!
Copyright © 2006-08-29 by Tak Auyeung