q for the C hackers
David Long
dave at jumpshift.com
Tue Aug 19 10:27:37 EDT 2003
> However, what is the convention in C? There seem to be two fine ways
> of doing it -- using the preprocessor, or the const keyword:
>
> #define NUMBER_OF_UNITS 8
>
> const int NUMBER_OF_UNITS = 8;
>
>
>
> I'm just interested in hearing about whether one is more appropriate
> than the other in some contexts. Thanks.
I would stick with defines. More modern languages have the option of
effectively treating a "const" declaration as an immediate value, but I
do not believe that C can. However there are times when a declaration
which allocates storage is necessary, as when you need to pass a pointer
to a value. Also, for strings the C standard requires each literal
string constant to occupy unique read/write storage (in case the code
decides to rewrite part of it). Therefore allocating a (optionally
const) variable will use less storage than repeated use of a define'd
string constant. Alternatively most compilers provide an option for
making string constants read-only.
The "const" type modifier is part of the ANSI/ISO C language standard
(as is "void" and various other post K&R enhancements).
-dl
--
David A. Long
JumpShift, LLC
dave at jumpshift.com
More information about the gnhlug-discuss
mailing list