Search code examples
cvariadic-functions

How to make a __VA_ARGS__ macro which can be called with no arguments?


I have a macro:

#define debug(fmt, ...) printf("%lu %s:%s:%i " fmt, ms(), __FILE__, __func__, __LINE__, __VA_ARGS__)

which does just what I want.

I can call it with:

debug("i: %i\n", i);

to print the value of i.

My problem is that I can't call it with:

debug("got here");

as that expands to:

printf("%lu %s:%s:%i %s " "got here", ms(), __FILE__, __func__, __LINE__,)

which is a trailing-comma bug.

How can I change my __VA_ARGS__ macro so that it can handle the "no variables"/"only format string" case?


Solution

  • You can do it in two steps:

    #define debug(...) DEBUG(__VA_ARGS__, "")
    #define DEBUG(fmt, ...) printf("%lu %s:%s:%i " fmt "%s", ms(), __FILE__, __func__, __LINE__, __VA_ARGS__)
    
    debug("%d\n", 42);
    debug("Hello\n");
    

    In this way, even if you don't pass a second param it is replaced by an "" and results in a NOP.