I am trying to write a C variadic macro that checks if it was invoked with one, or many arguments.
I found some solutions which use a macro that counts the arguments, but those solutions are either for a fixed/finite amount of arguments, or rely on the arguments sharing the same type:
#define VA_NARGS_IMPL(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
#define VA_NARGS(...) VA_NARGS_IMPL(__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
Counts arguments upto 10, then fails. However I think that checking 1 vs many arguments is an easier problem, so it might have a solution that will work with any type and for any number of arguments.
My use for this is in a sort of debug_log
macro:
#define debug_log(...) \
do { \
fprintf(verbose, " - %lu ", time(NULL)); \
if (VA_HAS_MANY_ARGS(__VA_ARGS__)) { \
fprintf(verbose, __VA_ARGS__); \
} else {
fprintf(verbose, "%s\n", __VA_ARGS__); \
} \
while (0)
Which can be invoked as debug_log("string here");
but also debug_log("string there %i\n", 5);
and will produce:
- current_time_here string here\n
- current_time_there string there 5\n
respectively.