Variadic Macro - Example

Example

If a printf-like function dbgprintf were desired, which would take the file and line number from which it was called as arguments, the following macro might be used:

// Our implemented function void realdbgprintf (const* char SourceFilename, int SourceLineno, const char *CFormatString, ...); // Due to a design bug of the variadic macro in C++, the following is more readable, but should be avoided. // Reason is, that dbgprintf("Hallo") will be expanded to realdbgprintf (__FILE__, __LINE__, "Hallo", ) // The comma before the closing brace will result in a syntax error ... //#define dbgprintf(cformat, ...) realdbgprintf (__FILE__, __LINE__, cformat, __VA_ARGS__) // GNU C++ supports the non portable extention: //#define dbgprintf(cformat, ...) realdbgprintf (__FILE__, __LINE__, cformat, ##__VA_ARGS__) // By using the cformat string as part of the variadic arguments we can avoid this. // This is tricky, but portable solution. #define dbgprintf(...) realdbgprintf (__FILE__, __LINE__, __VA_ARGS__)

dbgprintf could then be called as:

dbgprintf ("Hello, world");

which expands to:

realdbgprintf (__FILE__, __LINE__, "Hello, world");

or:

dbgprintf("%d + %d = %d", 2, 2, 5);

which expands to:

realdbgprintf(__FILE__, __LINE__, "%d + %d = %d", 2, 2, 5);

Without variadic macros, writing wrappers to printf is not directly possible. The standard workaround is to use the stdargs functionality of C/C++, and have the function call vprintf instead.

Read more about this topic:  Variadic Macro

Famous quotes containing the word example:

    Our intellect is not the most subtle, the most powerful, the most appropriate, instrument for revealing the truth. It is life that, little by little, example by example, permits us to see that what is most important to our heart, or to our mind, is learned not by reasoning but through other agencies. Then it is that the intellect, observing their superiority, abdicates its control to them upon reasoned grounds and agrees to become their collaborator and lackey.
    Marcel Proust (1871–1922)