Skip to content

Instantly share code, notes, and snippets.

@dhh1128
Last active October 5, 2019 11:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dhh1128/62770dd17c6632cf0abe to your computer and use it in GitHub Desktop.
Save dhh1128/62770dd17c6632cf0abe to your computer and use it in GitHub Desktop.
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
Copy link
Author

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