/*
This might be language abuse. Variadic macros, designated
initializers, structs, and compound literals makes it possible to
have named and optional parameters. Tested in gcc 4.5 and clang 1.1.
*/
#include <stdio.h>
#define foo(...) foo_((struct foo){__VA_ARGS__})
struct foo { const char *name; int number; };
void foo_(struct foo foo)
{
printf("%s: %d\n", foo.name ?: "untitled", foo.number);
}
int main(int argc, char **argv)
{
foo("three", 3);
foo("hello");
foo(.name = "zero");
foo(.number = argc, .name = "argc",);
foo(.number = 42);
return 0;
}
/* Output
three: 3
hello: 0
zero: 0
argc: 1
untitled: 42
*/
on July 21st, 2010 at 08:10 AM
Absolutely brilliant trick !!!
on August 8th, 2010 at 02:25 AM
I’ve discovered it some time ago, and published on StackOverflow: http://stackoverflow.com/questions/2325514/adding-default-arguments-to-variadic-macro/2325737#2325737
Please note that accessing struct members like ”.number” is GCC extension, but the rest is C99.