C语言宏函数重载

C语言宏函数重载

今天在一篇博客中学到了C语言宏函数重载的方法,在此记录一下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <stdio.h>

#define SUM1(A) (A)
#define SUM2(A, B) ((A) + (B))
#define SUM3(A, B, C) ((A) + (B) + (C))

#define GET_MACRO(_1, _2, _3, NAME, ...) NAME
#define SUM(...) \
GET_MACRO(__VA_ARGS__, SUM3, SUM2, SUM1) \
(__VA_ARGS__)

int main(void)
{
printf("%d\n", SUM(1));
printf("%d\n", SUM(1, 2));
printf("%d\n", SUM(1, 2, 3));

return 0;
}