May 01, 2006
Macros With Variable Length Argument Lists
Everyone knows, of course, that the preprocessor is evil. Except when you need it. The C99 standard enhanced the preprocessor in several areas, and the next revision of the C++ standard will include those changes. One that everyone should like is the addition of variable length argument lists for macros.
What that means is that you can now write that debugging macro without having to play games to hide the commas in your argument list:
#define output(target, ...) fprintf(target, __VA_ARGS__)
#define debug(...) output(stderr, __VA_ARGS__)
Those two levels of macros aren't really needed here, but I threw them in to show that you can have ordinary macro arguments before the ellipsis, but you don't have to. To use the debug macro, just do what you'd expect:
debug("at line " __LINE__);
debug("Value is %d\n", value);
debug("Coordinates are (%f,%f)\n", coord.x, coord.y)
Posted by Pete Becker at 09:26 AM Permalink
|