Search code examples
cvariadic

formatting with variadic variables


c89 gcc 4.7.4

I was just experimenting with macros like these:

#define LOG_INFO_1(fmt, ...) printf(fmt, __VA_ARGS__)
#define LOG_INFO_2(...) printf(__VA_ARGS__)

And using like this:

LOG_INFO_1("%s:%d", __func__, __LINE__);
LOG_INFO_2("%s:%d", __func__, __LINE__);

The output gives exactly the same format. I am just wondering what is the advantage of having the fmt argument in my first macro? It doesn't seem to be really needed. How could I make use of it?


Solution

  • Specifying that the first parameter is fmt makes no difference to the compiler/computer.

    However, I think it makes a big difference to other programmers who may use your code.

    Looking at LOG_INFO_1(fmt, ...), I see a strong hint that this macro takes a printf-style format string with additional parameters after.

    Looking at LOG_INFO_2(...), I have no idea what parameters should be passed, or in what order. Maybe the first parameter should be a RFC 5424 severity code? Maybe it should be an output stream to write to? Nothing in the macro hints at the answer.

    I think you should make work easier for the programmers who come after you by specifying as much as possible, and only leaving ambiguities such as ... only where absolutely necessary.