HP aC++/HP C A.06.25 Programmer's Guide
Parentheses surrounding each argument and the resulting expression ensure that the
precedences of the arguments and the result interact properly 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 that because each argument each argument to the MAX macro appears in the token
string more than once, the actual arguments to the MAX macro may have undesirable
side effects.
The following example may not work as expected because the argument a is
incremented two times when a is the maximum:
i = MAX(a++, b);
This expression is expanded to:
i = ((a) > (b) ? (a) : (b))
Given this macro definition, the statement
i = MAX(a, b+2);
is expanded to:
i = ((a) > (b+2) ? (a) : (b+2));
Example 1
#define isodd(n) ( ((n % 2) == 1) ? (TRUE) : (FALSE))
This macro tests a number and returns TRUE if the number is odd. It returns FALSE
otherwise.
Example 2
#define eatspace()while((c=getc(input))==c==’\n’c\ = ‘t’ )
This macro skips white spaces.
Using Constants and Inline Functions Instead of Macros
In C++ you can use named constants and inline functions to achieve results similar to
using macros. You can use const variables in place of macros. You can also use inline
functions in many C++ programs where you would have used a function-like macro
in a C program. Using inline functions reduces the likelihood of unintended side effects,
since they have return types and generate their own temporary variables where
necessary.
Example
The following program illustrates the replacement of a macro with an inline function:
164 Preprocessing Directives