Tuesday, September 15, 2009

The #define Directive

We can use the #define directive to give a meaningful name to a constant in our program. The syntax is:
#define identifier token-string
The #define directive substitutes token-string for all subsequent occurrences of an identifier in the source file. The identifier is replaced only when it forms a token. For example,
#define SUM x+y
The identifier remains defined and can be tested using the #if defined and #ifdef directives.

Formal parameter names appear in token-string to mark the places where actual values are substituted. Each parameter name can appear more than once in token-string, and the names can appear in any order. The number of arguments in the call must match the number of parameters in the macro definition. Liberal use of parentheses ensures that complicated actual arguments are interpreted correctly. For example,
#define AVG(a,b) (((a)+(b))/2)

No comments:

Post a Comment