THE PREPROCESSOR
The define statement is used to make programs more readable, and allow the inclusion of macros. Consider the following examples,
#define TRUE 1 /* Do not use a semi-colon , # must be first character on line */
#define FALSE 0
#define NULL 0
#define AND &
#define OR |
#define EQUALS ==
game_over = TRUE;
while( list_pointer != NULL )
................
MACROS
Macros are inline code which are substituted at compile time. The definition of a macro, which accepts an argument when referenced,
#define SQUARE(x) (x)*(x)
y = SQUARE(v);
In this case, v is equated with x in the macro definition of square, so the variable y is assigned the square of v. The brackets in the macro definition of square are necessary for correct evaluation.
The expansion of the macro becomes y = (v) * (v);
Naturally, macro definitions can also contain other macro definitions,
#define IS_LOWERCASE(x) (( (x)>='a') && ( (x) <='z') )
#define TO_UPPERCASE(x) (IS_LOWERCASE (x)?(x)-'a'+'A':(x))
while(*string) {
*string = TO_UPPERCASE (*string);
++string;
}
CONDITIONAL COMPILATIONS
These are used to direct the compiler to compile/or not compile the lines that
follow
#ifdef NULL
#define NL 10
#define SP 32
#endif
In the preceding case, the definition of NL and SP will only occur if NULL has been defined prior to the compiler encountering the #ifdef NULL statement. The scope of a definition may be limited by
#undef NULL
This renders the identification of NULL invalid from that point onwards in the source file.
Typedef
This statement is used to classify existing C data types, eg,
typedef int counter; /* redefines counter as an integer */
counter j, n; /* counter now used to define j and n as integers */
typedef struct {
int month, day, year;
} DATE;
DATE todays_date; /* same as struct date todays_date */