c语言变参的宏定义

#define debug(format, ...) fprintf(stderr, format, __VA_ARGS__)

等价于:

#define debug(format, args...) fprintf (stderr, format, args)

C99规范支持了可变参数的宏,可以用VA_ARGS传递…。
用法如下:

#include <stdio.h>

#define DEBUG(format, ...) printf(format, __VA_ARGS__)

int main(){
        int turn=1;

        printf("enter %s\n", __func__);
        DEBUG("test:%d\n",turn);
        return  0;
}

但这样又引入了一个新的问题,当…为空时,会导致链接错误。这里引入’##’操作。如果可变参数被忽略或为空,’##’操作将使预处理器(preprocessor)去除掉它前面的那个逗号。

#include <stdio.h>

#define DEBUG(format, ...) printf(format, ##__VA_ARGS__)

int main(){
        int turn=1;

        printf("enter %s\n", __func__);
        DEBUG("test:%d\n",turn);
        DEBUG("test\n");
        return  0;
}

参考:
宏中"#"和"##"的用法

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注