话不多说,参见如下代码
#include <stdio.h>
#define test(a, ...) test_core(a,(NULL,##__VA_ARGS__))
int test_core(int a, char *ptr){
if(ptr == NULL){
return a+10;
}
printf("%s\n", ptr);
return a+100;
}
int main(){
int a = test(10);
printf("a is %d\n", a);
a = test(10, "hello, suprise!");
printf("a is %d\n", a);
}
运行结果:
a is 20
hello, suprise!
a is 110
关键点是逗号运算符和##__VA_ARGS__
结合使用。当用户不输入参数时,##__VA_ARGS__
为空,那么自然test_core的第二个参数为NULL。而当用户输入参数时,这时宏展开为test_core(a,(NULL,"hello,suprise!"))
,而又因为逗号运算符的性质,括号里面的返回值实际上是"hello,suprise"
,从而达到函数默认值的效果。