arut wrote:
I would like to know when a const should be used and when a #define is necessary
in a program using a constant. What are the pros and cons?
In general, think of macros as a purely textual replacement. Think of a
const variable as being a read-only variable.
Because of the textual nature of preprocessing, macros are usually
considered less type-safe, beause type information is often not included
in the #define. You could try to get around this by casting the value
within the macro itself, but this is usually considered bad form because
it circumvents the C type system. Using type suffixes for numerical
values alleviates this problem, for the most part (ie 123UL notifies the
compiler that the type of 123 is unsigned long).
Scoping rules are also different. Macros have file scope, where const
variables have scope that corresponds to where they are declared.
There are several rules of thumb I use when deciding which to use.
There aren't that many hard and fast rules; for the most part it's all a
matter of degree.
1. If the scope that the 'constant' is used in is small or isolated,
prefer a const variable allocated in automatic storage (ie stack). It
will most likely be optimized away by your compiler.
2. If the constant will be used to specify the size for an array in
automatic storage, choose a macro (until I can recommend C99 VLA's in
good concience).
3. If you need a constant across a bunch of functions or files, use a
macro. Using a const variable with static storage (even if it's
declared static) will result in a permanent static storage location
being allocated for it.
4. If your expression is complicated, try to break it up into smaller
chunks of const variables that are initialized via macros:
/* Example of breaking down a complex calculation */
void do_calculation(float circle_radius)
{
/* Do some kind of complex calculation: */
const float area = PI * (circle_radius * circle_radius);
const float foo = (area * FROB_CONSTANT) % FLUX_DIVISOR;
/* Now do something with it... */
}
Now for the rules just about everybody agrees on. These are mandatory!
1. Always use all caps for macro names.
2. Always use underscores to seperate words in macro names.
3. Always use type suffixes for numerical constants.
I think I hit about everything. Did I leave anything out?
Mark
Mark Haigh
mf*****@sbcglobal.ten