Variadic Macro - The Impossible Example

The Impossible Example

Unfortunately it is (still) not possible to write a carefree and secure macro in portable C++:

MYLOG(FormatLiteral, ...) fprintf (stderr, "%s(%d): " FormatLiteral "\n", __FILE__, __LINE__, __VA_ARGS__)

The following application works

MYLOG("Too many balloons %u", 42);

which expands to

fprintf (stderr, "%s(%u): " "Too many balloons %d" "\n", 42);

which is equivalent to

fprintf (stderr, "%s(%u): Too many balloons %d\n", 42);

But look at this application:

MYLOG("Attention!");

which expands to

fprintf (stderr, "%s(%u): " "Attention!" "\n", );

which generates a syntax error. There's no way to fix this behaviour!

GCC supports the following (non-portable) extention:

MYLOG(FormatLiteral, ...) fprintf (stderr, "%s(%u): " FormatLiteral "\n", __FILE__, __LINE__, ##__VA_ARGS__)

which removes the trailing comma when __VA_ARGS__ is empty.

Read more about this topic:  Variadic Macro

Famous quotes containing the word impossible:

    ... women learned one important lesson—namely, that it is impossible for the best of men to understand women’s feelings or the humiliation of their position. When they asked us to be silent on our question during the War, and labor for the emancipation of the slave, we did so, and gave five years to his emancipation and enfranchisement.... I was convinced, at the time, that it was the true policy. I am now equally sure that it was a blunder.
    Elizabeth Cady Stanton (1815–1902)