Summary: A function-like macro accepts arguments, like a function.
Some languages use the term “macro” when referring to replacement text. In C, a macro can do more than simply replace text. It can also accept arguments in much the same way that a function does. In this case the replacement text is called a “function-like macro.”
A well-designed macro can be every bit as useful as a function. In fact, some C
library routines are implemented as macros rather than C functions.
The MACRO.C program below has a macro that works like the abs library function, returning the absolute value of any integer. The macro uses the conditional operator (? :), which we explained in Chapter 6.
/* MACRO.C: Demonstrate macros. */
#include <stdio.h>
#define ABS(value) ( (value) >= 0 ? (value) : -(value) )
main()
{
int val = -20;
printf( “result = %d\n”, ABS(val) );
}
The ABS macro behaves much like a function. You can “call” it by name, passing it an argument you want to process. The macro is defined in the following program line:
#define ABS(value) ( (value) >= 0 ? (value) : -(value) )
The parameter value appears four times in the macro—once in the macro name ABS and three times in the replacement text that follows the name.
Summary: Always enclose macro parameters in parentheses.
To avoid unwanted side effects, you should always enclose macro parameters in parentheses. If the parameter passed to the ABS macro is an expression containing operators, the lack of parentheses could cause operator-precedence errors. For more information, see “Omitting Parentheses from Macro Arguments”.
Function-like macros, like other #define directives, are expanded during the preprocessor phase of compilation, before QuickC translates any executable statements. When QuickC encounters the line
printf( “result= %d\n”, ABS(val) );
it expands it to read:
printf( “result= %d\n”, ( (val) >= 0 ? (val) : -(val) ) );
Summary: Macros can improve readability.
A macro can improve a program's readability by describing the nature of an operation while hiding its complex details. Most people find the first of the two statements above easier to understand than the expanded version.
Function-like macros are fast, too. Since a macro creates inline code, it doesn't have the overhead associated with a normal function call. On the other hand, each use of a macro inserts the same code in your program, whereas a function definition occurs only once. So while macros can be faster than functions, they can also bloat the size of the executable file.