Last active
October 5, 2019 11:46
-
-
Save dhh1128/62770dd17c6632cf0abe to your computer and use it in GitHub Desktop.
the "paired, sliding arg list" macro trick
This file contains hidden or 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
// Accept any number of args >= N, but expand to just the Nth one. In this case, | |
// we have settled on 5 as N. We could pick a different number by adjusting | |
// the count of throwaway args before N. Note that this macro is preceded by | |
// an underscore--it's an implementation detail, not something we expect people | |
// to call directly. | |
#define _GET_NTH_ARG(_1, _2, _3, _4, N, ...) N | |
// Count how many args are in a variadic macro. Only works for up to N-1 args. | |
#define COUNT_VARARGS(...) _GET_NTH_ARG(__VA_ARGS__, 4, 3, 2, 1) | |
int main() { | |
printf("one arg: %d\n", COUNT_VARARGS(1)); | |
printf("three args: %d\n", COUNT_VARARGS(1, 2, 3)); | |
} | |
// ------ output -------- | |
one arg: 1 | |
three args: 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Based on a technique described here: http://stackoverflow.com/a/11763277