69,382
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#define DEFARG(name, defval) ((#name[0]) ? (name + 0) : defval)
int _f1(int i)
{
return 2*i;
}
#define f1(arg0) _f1(DEFARG(arg0, 0))
int _f2(int i, int j)
{
return i + j;
}
#define f2(arg0, arg1) _f2(DEFARG(arg0, 0), DEFARG(arg1, 1))
int main()
{
printf("%d\n", f1());
printf("%d\n", f1(1));
printf("%d\n", f2(,));
printf("%d\n", f2(2,));
printf("%d\n", f2(, 3));
printf("%d\n", f2(4, 5));
return 0;
}
#define DEFARG(name, defval) ((#name[0]) ? (name + 0) : defval)
/*这里,DEFARG是宏名,(name,defval)是他的两个参数名。后面的括号内容是参数的定义方式。这里可以把这个宏看作一个函数,不过他是与处理的:
当#name[0]为真时(无参数),返回name+0;
当#name[0]为假时(有参数),返回defval(默认值)
*/
比如:
#define f1(arg0) _f1(DEFARG(arg0, 0))
/*对于f1()的调用,因为#name[0]为真(没有传递参数),所以返回name+0=0;
对于f1(1)的调用,因为#name[0]为假(有参数传递),所以返回defval=1;
*/
又比如:
#define f2(arg0, arg1) _f2(DEFARG(arg0, 0), DEFARG(arg1, 1))
/*对于f2(,)的调用,因为#name[0]为真(没有传递arg0参数),所以返回arg0+0=0;
因为#name[1]为假(有传递arg1参数),所以返回arg1=1;
所以输出为1;
对于f2(2,0)的调用,参考上面分析:结果为2+1=3;
*/
下面这篇文章有很详细的介绍,可以了解一下
blog.163.com/xuwenqiang_1989/blog/static/49074935201132433318770/