Parameterized Macros
To form a parameterized macro:
#define identifier(parameterlist) replacement-list
There must be no spaces between the identifier and the
parameter list. There must be no spaces in the parameter list.
Parameterized macros often serve as simple functions.
Examples of parameterized macros:
#define getchar() getc(stdin)
#define max(x,y) (((x)>(y))?(x):(y))
#define toupper(c) (('a'<=(c)&&(c)<='z')?(c)-'a'+'A':(c))
Advantages of using a parameterized macro instead of a function:
- The compiled code will execute more rapidly because the macro is
substituted in line. No function calling overhead is required.
- Macros are "generic." That is, the parameters are not typed like they are in functions.
So, for example, the max() macro above will work for floats just as well as for ints.
Disadvantages of using a parameterized macro instead of a function:
- The compiled code will often be larger, particularly when macros are nested
(e.g., max(a,max(b,max(c,d))) ) because each instance of the macro is
expanded in line.
- It is not possible to have a pointer to a macro.
- A macro may evaluate its arguments more than once, causing subtle errors.
Parameterized macros can be used to create templates for commonly used segments of code:
#define print(x) printf("%d\n",x)
print(i/j) /* becomes printf("%d\n",i/j); */