HP C A.06.05 Reference Manual
Preprocessing Directives
Macro Replacement (#define, #undef)
Chapter 7192
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
operators that might be used with the MAX macro.
Using a macro definition for MAX has some advantages over a function definition. First, it
executes faster because the macro generates in-line code, avoiding the overhead of a function
call. Second, the MAX macro accepts any argument types. A functional implementation of MAX
would be restricted to the types defined for the function. Note further that because each
argument to the MAX macro appears in the token string more than once, check to be sure that
the actual arguments to the MAX macro do not have any "side effects." The following example
MAX(a++, b);
might not work as expected because the argument a is incremented two times when a is the
maximum.
The following statement
i = MAX(a, b+2);
is expanded to:
i = ((a) > (b+2) ? (a) : (b+2));
Examples
#define isodd(n) ( ((n % 2) == 1) ? (TRUE) : (FALSE))
/* This macro tests a number and returns TRUE if the number is odd. It will
*/
/* return FALSE otherwise..........................*/