Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
the "paired, sliding arg list" macro trick
// 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
@dhh1128

This comment has been minimized.

Copy link
Owner Author

@dhh1128 dhh1128 commented Nov 21, 2014

Based on a technique described here: http://stackoverflow.com/a/11763277

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment