在#define中使用参数可以创建外形和作用与函数类似的类函数宏。带有参数的宏看上去很像函数,因为这样的宏也使用圆括号。类函数宏定义的圆括号中可以有一个或多个参数,随后这些参数出现在替换体中,如下图所示。
C语言之在#define中使用参数
Parts of a function-like macro definition
下面是一个类函数宏的示例:
#define SQUARE(X) X*X
在程序中可以这样用:
z = SQUARE(2);
这看上去像函数调用,但是它的行为和函数调用完全不同。程序macarg.c 演示了类函数宏和另一个宏的用法。该示例中有一些陷阱,请读者仔细阅读序。
The macarg.c Program
/mac_arg.c -- macros with arguments/
#include
#define SQUARE(X) X*X
#define PR(X) printf("The result is %d.n", X)
int main(void)
{
int x = 5;
int z;
printf("x = %dn", x);
z = SQUARE(x);
printf("Evaluating SQUARE(x): ");
PR(z);
z = SQUARE(2);
printf("Evaluating SQUARE(2): ");
PR(z);
printf("Evaluating SQUARE(x+2): ");
PR(SQUARE(x+2));
printf("Evaluating 100/SQUARE(2): ");
PR(100/SQUARE(2));
printf("x is %d.n", x);
printf("Evaluating SQUARE(++x): ");
PR(SQUARE(++x));
printf("After incrementing, x is %x.n", x);
return 0;
}
SQUARE宏的定义如下:
#define SQUARE(X) XX
这里,SQUARE是宏标识符,SQUARE(X)中的X是宏参数,XX是替换列表。程序清单16.2中出现SQUARE(X)的地方都会被XX替换。这与前面的示例不同,使用该宏时,既可以用X,也可以用其他符号。