Created
March 23, 2019 13:06
-
-
Save otaon/94db79fa3eca66bf36ddc331b8d51e2d to your computer and use it in GitHub Desktop.
C言語 - gccで可変長引数マクロを使用する方法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// gccでは...で表した可変長引数を__VA_ARGS__で指定できる | |
// 可変長引数を全て__VA_ARGS__とマップする | |
#define DEBUG_PRINT(...) printf(__VA_ARGS__); fflush(stdout) | |
// fmt以降の可変長引数を__VA_ARGS__とマップする | |
#define DEBUG_PRINT2(fmt, ...) printf(fmt, __VA_ARGS__); fflush(stdout) | |
// _1,_2,_3,の部分・・・引数の個数だけ用意する | |
// NAME・・・この部分に、目的の引数個数用の関数名が入る | |
#define GET_MACRO(_1,_2,_3,NAME,...) NAME | |
// (SUMの引数, sum3, sum2)(SUMの引数)に変換される | |
#define SUM(...) GET_MACRO(__VA_ARGS__, sum3, sum2)(__VA_ARGS__) | |
// 2変数版sum | |
int sum2(int a,int b) { return a+b; } | |
// 3変数版sum | |
int sum3(int a,int b,int c) { return a+b+c; } | |
// マクロの使い方 | |
printf("SUM(2,3)=%d\n", SUM(2,3)); // GET_MACRO(2,3, sum3, sum2)(2,3); -> sum2(2,3); | |
printf("SUM(2,3,4)=%d\n", SUM(2,3,4)); // GET_MACRO(2,3,4, sum3, sum2)(2,3,4); -> sum3(2,3,4); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment