Simple Macros

To form a simple macro:

#define identifier replacement-list

There must be at least one space between the #define directive and the identifier and between the identifier and the replacement-list. The replacement-list can be any sequence of C tokens, including identifiers, keywords, numbers, character constants, string literals, operators and punctuation. The C preprocessor substitutes any occurance of the identifier with the entire replacement-list.

Simple macros are used for:

  • Defining "manifest constants"
  • Making minor changes to the syntax of C
  • Renaming types
  • Indicating a compile-time condition
  • Examples of simple macros:

    #define N 100
    #define PI 3.14159
    #define WARNING "Warning: nonstandard feature"
    #define begin {
    #define end }
    #define boolean int
    #define DEBUG
    In the above, N and PI are manifest constants. The begin and end macros can be used in place of the begin and end block ({}) symbols, thus making C look sort of like Pascal. The boolean definition allows you to declare boolean type variables (which are really int types). And the DEBUG can identify a debug version of the program to the preprocessor.

    Advantages of defining manifest constants:

  • Programs are easier to read.
  • Programs are easier to modify.
  • Helps reduce error of inconsistant use, as well as typographical errors.
  • Warning: Don't put any extraneous symbols in a macro definition; these will become part of the replacement list:

    #define N = 100

    int a[N]; /* becomes int a[= 100]; */