HP C/iX Reference Manual (31506-90011)
104 Chapter7
Preprocessing Directives
Macro Replacement
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];
In this example, the array x is dimensioned using the macro ARRAY_SIZE rather than the
constant 1000. Note that expressions that may use the array can also use the macro
instead of the actual constant:
for(i=0; i<ARRAY_SIZE; i) f+=x[i];
Changing the dimension of x means only changing the macro for ARRAY_SIZE; the
dimension will change and so will all the expressions that make use of the dimension.
Some other common macros used by C programmers include:
#define FALSE 0
#define TRUE 1
The following macro is more complex. It has two parameters and will produce an in-line
expression which is equal to the maximum of its two parameters:
#define MAX(x,y) ((x) > (y) ? (x) : (y))
Parentheses surrounding each argument and the resulting expression insure that the
precedences of the arguments and the result will not improperly interact with any other