Use const instead of #define constants

Never use #define for symbolic constants. Instead, use the C++ const storage class. As with #define symbols, const declarations are evaluated at compile time (for types and expressions that qualify as compile-time constants). Unlike #define symbols, they follow the C scope rules and have types associated with them. You can also use enum to prevent a host of problems. For example:

      #define kGreen 1                    // Bad
      const int kGreen = 1;               // Better
      enum Color {kRed, kGreen, kBlue}    // Best
If you accidentally redefine a name with a #define, the compiler silently changes the meaning of your program. With const or enum you get an error message. Even better, with enum you can put the identifiers in the scope of a class (see
"Use global names only for classes" on page 61). As an added bonus, each enumeration is treated as a separate type for purposes of type checking (much like the way scalars are handled in Pascal) and for purposes of overloading.

Unlike in ANSI C, objects in C++ that are declared const and initialized with compile-time expressions are themselves compile-time constants (but only if they are of integral or enumeration type). Thus, they can be used as case labels or in compile-time expressions.

[Contents] [Previous] [Next]
Click the icon to mail questions or corrections about this material to Taligent personnel.
Copyright©1995 Taligent,Inc. All rights reserved.

Generated with WebMaker