Skip to content

Instantly share code, notes, and snippets.

@pervognsen
Created March 10, 2017 22:11
Show Gist options
  • Select an option

  • Save pervognsen/180a85811b2ef094349a9d83a0a904b5 to your computer and use it in GitHub Desktop.

Select an option

Save pervognsen/180a85811b2ef094349a9d83a0a904b5 to your computer and use it in GitHub Desktop.
// Two techniques for using C99 variadic macros to provide a nicer interface to variadic functions.
#include <stdarg.h>
#include <stdio.h>
enum { SENTINEL = 0xDEADBEEF };
void vprint_sentinel(void *dummy, ...) {
va_list args;
va_start(args, dummy);
for (;;) {
int x = va_arg(args, int);
if (x == SENTINEL) break;
printf("%d ", x);
}
printf("\n");
va_end(args);
}
#define print_sentinel(...) vprint_sentinel(0, __VA_ARGS__, SENTINEL)
void vprint_length(size_t n, ...) {
va_list args;
va_start(args, n);
for (size_t i = 0; i < n; i++)
printf("%d ", va_arg(args, int));
printf("\n");
va_end(args);
}
// This handles a maximum of 4 arguments.
#define sel(_0, _1, _2, _3, _4, ...) _4
#define len(...) sel(__VA_ARGS__, 4, 3, 2, 1, 0)
#define print_length(...) vprint_length(len(__VA_ARGS__), __VA_ARGS__)
int main() {
print_sentinel(1, 2, 3, 4);
print_length(1, 2, 3, 4);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment