Aussie AI
Variable-Argument Debug Macros
- 
                                            Book Excerpt from "Generative AI in C++"
 
- 
                                            by David Spuler, Ph.D.
 
Variable-Argument Debug Macros
A neater solution is to use varargs preprocessor macros with the special tokens “...” and “__VA_ARGS__”,
which are standard in C and C++ (since 1999):
   #define ydebug(fmt,...)  fprintf(stderr, (fmt), __VA_ARGS__ )
   ...
   ydebug("DEBUG: I am here!\n");
That's not especially helpful, so we can add more context:
    // Version with file/line/function context
    #define ydebug(fmt,...)  \
        ( fprintf(stderr, "DEBUG [%s:%d:%s]: ", \
                __FILE__, __LINE__, __func__ ), \
        fprintf(stderr, (fmt), __VA_ARGS__ ))
   ...
   ydebug("I am here!\n");
This will report the source code filename, line number, and function name.
Note the use of the comma operator between the two fprintf statements (whereas a semicolon would be a macro bug).
Also required are parentheses around the whole thing, and around each use of the “fmt” parameter.
Here's a final example that also detects if you forgot a newline in your format string (how kind!):
    // Version that makes the newline optional
    #define ydebug(fmt,...)  \
        (fprintf(stderr, "DEBUG [%s:%d:%s]: ", \
                __FILE__, __LINE__, __func__ ), \
        fprintf(stderr, (fmt), __VA_ARGS__ ), \
        (strchr((fmt), '\n') != NULL \
                || fprintf(stderr, "\n")))
   ...
   ydebug("I am here!");  // Newline optional
	
| 
 • Next: • Up: Table of Contents  | 
 
 | 
The new AI programming book by Aussie AI co-founders:
 Get your copy from Amazon: Generative AI in C++  |