Skip to content

Instantly share code, notes, and snippets.

@catharinejm
Last active December 15, 2015 17:38
Show Gist options
  • Save catharinejm/5297300 to your computer and use it in GitHub Desktop.
Save catharinejm/5297300 to your computer and use it in GitHub Desktop.
C arg stuff
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#ifndef __COUNTER__
#error "Your C compiler doesn't support __COUNTER__. Try GCC >= 4.3 or Clang"
#endif
#define __GENSYM2(x,y) x ## y
#define __GENSYM1(x,y) __GENSYM2(x,y)
#define __GENSYM(x) __GENSYM1(x ## __gensym__, __COUNTER__)
#define __extract__2(ary, last, atype_t, args, ary_c, args_c) \
atype_t *ary_c; \
atype_t args_c; \
va_list args; \
va_start(args, last); \
ary_c = ary; \
while ((args_c = va_arg(args, atype_t))) \
*ary_c++ = args_c; \
*ary_c = NULL; \
va_end(args)
#define __extract(ary, last, atype_t) \
__extract__2(ary, last, atype_t, __GENSYM(args), __GENSYM(ary_c), __GENSYM(args_c))
char * join_ary(char * dest, char * sep, char ** ary) {
char ** s = ary;
while (*s) {
strcat(dest, *s);
if (*++s) strcat(dest, sep);
}
return dest;
}
char * join_args(char * dest, char * sep, ...) {
char *ary[128];
__extract(ary, sep, char*);
return join_ary(dest, sep, ary);
}
char * jstrcat(char * dest, ...) {
char *ary[128];
__extract(ary, dest, char*);
return join_ary(dest, "", ary);
}
int main(int argc, char * argv[]) {
if (argc < 2) {
fprintf(stderr, "NEEDS ARG!\n");
return 1;
}
char buf[512] = { '\0' };
char *ary[] = { "First", "Second", "Third", NULL };
join_ary(buf, argv[1], ary);
printf("join_ary: %s\n", buf);
buf[0] = '\0';
join_args(buf, argv[1], "Hitotsu", "Futatsu", "Mittsu", NULL);
printf("join_args: %s\n", buf);
buf[0] = '\0';
jstrcat(buf, "foo", "bar", "baz", NULL);
printf("jstrcat: %s\n", buf);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment