Variadic macro

A variadic macro is a feature of some computer programming languages, especially the C preprocessor, whereby a macro may be declared to accept a varying number of arguments.

Variable-argument macros were introduced in 1999 in the ISO/IEC 9899:1999 (C99) revision of the C language standard, and in 2011 in ISO/IEC 14882:2011 (C++11) revision of the C++ language standard.[1] Support for variadic macros with no arguments was added in C++20.[2]

Declaration syntax

The declaration syntax is similar to that of variadic functions: a sequence of three full stops "..." is used to indicate that one or more arguments must be passed. During macro expansion each occurrence of the special identifier __VA_ARGS__ in the macro replacement list is replaced by the passed arguments.

No means is provided to access individual arguments in the variable argument list, nor to find out how many were passed. However, macros can be written to count the number of arguments that have been passed.[3]

Both the C99 and C++11 standards require at least one argument, but since C++20 this limitation has been lifted through the __VA_OPT__ functional macro. The __VA_OPT__ macro is replaced by its argument when arguments are present, and omitted otherwise. Common compilers also permit passing zero arguments before this addition, however.[4][5]

Support

Several compilers support variable-argument macros when compiling C and C++ code: the GNU Compiler Collection 3.0,[4] Clang (all versions),[6] Visual Studio 2005,[5] C++Builder 2006, and Oracle Solaris Studio (formerly Sun Studio) Forte Developer 6 update 2 (C++ version 5.3).[7] GCC also supports such macros when compiling Objective-C.

Support for the __VA_OPT__ macro to support zero arguments has been added in GNU Compiler Collection 8,[8] Clang 6,[9] but notably not Visual Studio 2017.[10]

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 solution applies.

// Our implemented function
void realdbgprintf (const char *SourceFilename,
                    int SourceLineno,
                    const char *CFormatString,
                    ...);

// Due to limitations of the variadic macro support in C++11 the following
// straightforward solution can fail and should thus be avoided:
//
//   #define dbgprintf(cformat, ...) \
//     realdbgprintf (__FILE__, __LINE__, cformat, __VA_ARGS__)
//
// The reason is that
//
//   dbgprintf("Hallo")
//
// gets expanded to
//
//   realdbgprintf (__FILE__, __LINE__, "Hallo", )
//
// where the comma before the closing brace will result in a syntax error.
//
// GNU C++ supports a non-portable extension which solves this.
//
//   #define dbgprintf(cformat, ...) \
//     realdbgprintf (__FILE__, __LINE__, cformat, ##__VA_ARGS__)
//
// C++20 eventually supports the following syntax.
//
//   #define dbgprintf(cformat, ...) \
//     realdbgprintf (__FILE__, __LINE__, cformat __VA_OPT__(,) __VA_ARGS__)
//
// By using the 'cformat' string as part of the variadic arguments we can
// circumvent the abovementioned incompatibilities.  This is tricky but
// portable.
#define dbgprintf(...) realdbgprintf (__FILE__, __LINE__, __VA_ARGS__)

dbgprintf() could then be called as

dbgprintf ("Hello, world");

which expands to

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

Another example is

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.

Trailing comma

There is a portability issue with generating a trailing comma with empty args for variadic macros in C99. Some compilers (e.g., Visual Studio[5]) will silently eliminate the trailing comma. Other compilers (e.g.: GCC[4]) support putting ## in front of __VA_ARGS__.

# define MYLOG(FormatLiteral, ...)  fprintf (stderr, "%s(%u): " 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 %u" "\n", __FILE__, __LINE__, 42);

which is equivalent to

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

But look at this application:

MYLOG("Attention!");

which expands to

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

which generates a syntax error with GCC.

GCC supports the following (non-portable) extension:

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

which removes the trailing comma when __VA_ARGS__ is empty.

Alternatives

Before the existence of variable-arguments in C99, it was quite common to use doubly nested parentheses to exploit the variable number of arguments that could be supplied to the printf() function:

# define dbgprintf(x) realdbgprintf x

dbgprintf() could then be called as:

dbgprintf (("Hello, world %d", 27));

which expands to:

realdbgprintf ("Hello, world %d", 27);
gollark: I mean, I actually can due to tux1ous forms.
gollark: I can't believe this.
gollark: You don't know about the CURRENTLY BEST AVAILABLE audio codec?!
gollark: No, opus is better.
gollark: > .mp3

References

  1. Working draft changes for C99 preprocessor synchronization – http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2004/n1653.htm
  2. "Comma omission and comma deletion". July 12, 2017. Retrieved June 14, 2018.
  3. Laurent Deniau (2006-01-16). "__VA_NARG__". Newsgroup: comp.std.c. Usenet: dqgm2f$ije$1@sunnews.cern.ch.
  4. Variadic Macros – Using the GNU Compiler Collection (GCC)
  5. Variadic Macros (C++)
  6. Clang source code change that mentions __VA_ARGS__ support (2006-07-29), note that Clang was open-sourced in 2007. http://llvm.org/viewvc/llvm-project?view=revision&revision=38770
  7. Sun Studio feature comparison – http://developers.sun.com/sunstudio/support/CCcompare.html
  8. "C++2a Support in GCC". Retrieved June 14, 2018.
  9. "C++ Support in Clang". Retrieved June 14, 2018.
  10. "Announcing: MSVC Conforms to the C++ Standard". May 7, 2018. Retrieved June 14, 2018.

See also

This article is issued from Wikipedia. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.