/*
  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
*/

2 Responses Follows

  1. akbar says

    Absolutely brilliant trick !!!

  2. qrdl says

    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.


Your Response