Home > OS >  C Macro to get only even variadic arguments passed
C Macro to get only even variadic arguments passed

Time:12-31

Would it be possible to make a ONLY_EVEN() macro to perform the following translations:

ONLY_EVEN0()
ONLY_EVEN2(a,b) b
ONLY_EVEN4(a,b,c,d) b,d

With any number of arguments, using variadic macro parameters?

CodePudding user response:

Probably not for an unbounded number of arguments.

However it is possible for any variable number of arguments up to an arbitrarily chosen bound. For example, below is a self-contained macro solution for any number of arguments in [0..6], which can be extended in the obvious way to support up to any limit you wish.

#define ONLY_EVEN0(a) 
#define ONLY_EVEN1(a) 
#define ONLY_EVEN2(a,b) b
#define ONLY_EVEN3(a,b,c) b
#define ONLY_EVEN4(a,b,c,d) b,d
#define ONLY_EVEN5(a,b,c,d,e) b,d
#define ONLY_EVEN6(a,b,c,d,e,f) b,d,f
#define ONLY_EVEN_N(a,b,c,d,e,f,n,...) ONLY_EVEN##n
#define ONLY_EVEN(...) ONLY_EVEN_N(__VA_ARGS__,6,5,4,3,2,1,0)(__VA_ARGS__)

// example:
0: ONLY_EVEN()
1: ONLY_EVEN(A)
2: ONLY_EVEN(A,B)
3: ONLY_EVEN(A,B,C)
4: ONLY_EVEN(A,B,C,D)
5: ONLY_EVEN(A,B,C,D,E)
6: ONLY_EVEN(A,B,C,D,E,F)
$ g   -std=c  11 -pedantic -E onlyeven.cpp | grep -v '#'
0:
1:
2: B
3: B
4: B,D
5: B,D
6: B,D,F

Note that by C/C spec the preprocessor is only guaranteed to accept up to 256 arguments.

  • Related