可变参数宏

预处理器

//... 接受任意数量的参数,
//__VA_ARGS__ 会把它们连同逗号一起粘贴进来
#define LOG(...) printf("[log] " __VA_ARGS__)

LOG("started\n");
//printed "[log] started"
LOG("x is %d, y is %d\n", 3, 4);
//输出 "[log] x is 3, y is 4"

//自 C23 起,__VA_OPT__(,) 只在有参数时才放入逗号,
//否则 DEBUG("no arguments") 会变成 printf("...",)
#define DEBUG(format, ...) printf("[debug] " format "\n" __VA_OPT__(,) __VA_ARGS__)
DEBUG("no arguments");
//输出 "[debug] no arguments"
DEBUG("%d + %d = %d", 2, 3, 2 + 3);
//printed "[debug] 2 + 3 = 5"

//参数变成数组:一个复合字面量,
//再由 sizeof 统计个数
int sumOf(const int numbers[], size_t count) {
    int sum = 0;
    for (size_t i = 0; i < count; i++) {
        sum += numbers[i];
    }
    return sum;
}
#define SUM(...) sumOf((int[]){__VA_ARGS__}, \
    sizeof((int[]){__VA_ARGS__}) / sizeof(int))

int total = SUM(1, 2, 3, 4);
//total is 10

//# 把所有参数变成一个字符串
#define TEXT(...) #__VA_ARGS__
const char *list = TEXT(red, green, blue);
//list is "red, green, blue"

printf("total is %d\n", total);
printf("list is %s\n", list);