HP C A.06.05 Reference Manual

Preprocessing Directives
Macro Replacement (#define, #undef)
Chapter 7 191
The formal parameters to the macro are separated with commas. They may or may not appear
in the replacement list. When the macro is invoked, the actual arguments are placed in a
parentheses-enclosed list following the macro name. Comma tokens enclosed in additional
matching pairs of parentheses do not separate arguments but are themselves components of
arguments.
The actual arguments replace the formal parameters in the token string when the macro is
invoked.
If a formal parameter in the macro definition directive's token string follows a # operator, it is
replaced by the corresponding argument from the macro invocation, preceded and followed by
a double-quote character (") to create a string literal. This feature may be used to turn macro
arguments into strings. This feature is often used with the fact that the compiler concatenates
adjacent strings.
After all replacements have taken place during macro invocation, each instance of the special
## token is deleted and the tokens preceding and following the ## are concatenated into a
single token. This is useful in forming unique variable names within macros.
The following example illustrates the use of the # operator for creating string literals out of
arguments and concatenating tokens:
#define debug(s, t) printf("x" # s "= %d, x" # t " %s", x ## s, x ## t)
Invoked as: debug(1, 2);
Results in:
printf("x" "1" "= %d, x" "2" "= %s", x1, x2);
which, after concatenation, results in:
printf("x1= %d, x2= %s", x1, x2);
Spaces around the # and ## are optional.
NOTE The # and ## operators are only supported in ANSI mode.
The most common use of the macro replacement is in defining a constant. Rather than hard
coding constants in a program, you can name the constants using macros then use the names
in place of actual constants. By changing the definition of the macro, you can more easily
change the program:
#define ARRAY_SIZE 1000
float x[ARRAY_SIZE];