Adding default arguments to variadic macro

vishal picture vishal · Feb 24, 2010 · Viewed 7k times · Source

Is it possible to add default arguments before variable argument in variadic macro? e.g I have the version of macro something like

#define MACRO(arg1, ...) func(arg1, ##__VA_ARGS__)

I would like to add 2 more default arguments in the macro before variable arguments so that it should not affect previous version. Like:

#define MACRO(arg1, arg2 = "", arg3 = "", ...) func(arg1, arg2, arg3, ##__VA_ARGS__)

Any help would be appreciated.

Answer

qrdl picture qrdl · Feb 24, 2010

What you can do:

struct foo {
    int   aaa;
    char  bbb;
    char  *ccc;
};

#define BAR(...)   bar((struct foo){__VA_ARGS__})

void bar(struct foo baz)
    /* set defaults */
    if (!baz.aaa)
        baz.aaa = 10;
    if (!baz.bbb)
        baz.bbb = 'z';
    if (!baz.ccc)
        baz.ccc = "default";

    printf("%d, %c, %s\n", baz.aaa, baz.bbb, baz.ccc);
}

...
BAR();                     // prints "10, z, default"
BAR(5);                    // prints "5, z, default"
BAR(5,'b');                // prints "5, b, default"
BAR(5, 'b', "something");  // prints "5, b, something"

Bad thing about this - zero parameter is treated like no parameter, e.g. BAR(0, 'c') will produce string 10, c, default