Saturday, May 22, 2010

#define vs. const

The const keyword is relatively new. Before const, #define was the only keyword available to define constants, so most older code uses #define directives. However,the useof const is preferred over #define for several reasons. First of all, C checks the syntax of const statements immediately. The #define directive is not checked until the macro is used. Also const use s C syntax, while the #define has a syntax all its own. Finally, const follows normal C scope rules, while constantsdefined by a #define directive continue on forever.

So, in most cases, a const statement is preferred over #define . Here are two ways of defining the same constant:

#define MAX 10 /* Define a value using the preprocessor */
/* (This definition can easily cause problems) */
const int MAX = 10; /* Define a C constant integer */
/* (safer) */

The #define directive can only define simple constants. The const statement can define almost any type of C constant, including things like structure classes. For example:
struct box {
int width, height; /* Dimensions of the box in pixels */
};
const box pink_box ={1.0, 4.5};/* Size of a pink box to be used for input */

The #define directive is, however, essential for things like conditional compilation
and other specialized uses.

Some compilers will not allow you to use a constant to define the size of an array. They should, but they have not caught up to the standard yet.

No comments:

Post a Comment