2005-07-30

__VA_ARGS__ + C99 compound literals = safe variadic functions

It occurred to me that new C features added by C99 standard can be used to implement „safe variadic functions“ that is, something syntactically looking like normal call of function with variable number of arguments, but in effect calling function with all arguments packed into array, and with array size explicitly supplied:
safe variadic functions
#define sizeof_array(arr) ((sizeof (arr))/(sizeof (arr)[0]))

/* 
 * NOTE: imagine that following macro definition is properly backslashified.
 *       And blame Google/Blogger for my not being able to do this.
 */
#define FOO(a, ...)
       foo((a), (char *[]){ __VA_ARGS__, 0 }, sizeof_array(((char *[]){ __VA_ARGS__ })))

int foo(int x, char **str, int n)
{
 printf("%i %i\n", x, n);
 while (n--)
  printf("%s\n", *(str++));
 printf("last: %s\n", *str);
}

int main(int argc, char **argv)
{
 FOO(1, "a", "boo", "cooo", "dd", argv[0]);
}
this outputs
1 5
a
boo
cooo
dd
./a.out
last: (null)
Expect me to use this shortly somewhere.
--Tags:-[]-[]-----------

2 comments:

  1. What was it in C99 that made this possible?

    ReplyDelete
  2. What was it in C99 that made this possible?

    Introduction of __VA_ARGS__ and compound literals (in C9X standard draft, to become later C99 standard).

    Of course, some compilers supported these features before.

    ReplyDelete