类函数宏:function-like-macro 用#define使用参数来定义宏,宏的参数用圆括号括起来,可以使一个参数或者多个参数,然后在使用的过程中这些参数将会被替换。
例如:
#define SQUARE(X) X*X //定义类函数宏
z = SQUARE(3); //使用类函数宏
源代码:
[root@rhel6164 test]# cat test.c
#include <stdio.h>
#define SQUARE(X) X*X
int squ_fun(int);
int main(void)
{
int x = 0;
printf("Please input one integer(n), and square(n+1) will be shown via two \
ways(function-like macro and general function). The default is 0.\n");
scanf("%d", &x);
printf("Evaluating SQUARE(3) is: %d \n", SQUARE(x+1));
printf("Evaluating squ_fun(3) is: %d \n", squ_fun(x+1));
return 0;
}
int squ_fun(int i)
{
int z = 0;
z = i * i;
return z;
}
编译&执行:
[root@rhel6164 test]# gcc test.c
[root@rhel6164 test]# ./a.out
Please input one integer(n), and square(n+1) will be shown via two ways(function-like macro and general function). The default is 0.
3
Evaluating SQUARE(3) is: 7
Evaluating squ_fun(3) is: 16
类函数宏只会做字符串替换(宏定义都只会做字符串替换),替换后为3+1*3+1,结果就是7;而一般函数就会把参数带进函数进行计算后返回结果,这里其实就是(3+1)*(3+1)。
友情链接:可变宏参数个数和可变函数参数个数