A variadic macro is a feature of some computer
programming language
A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language.
The description of a programming ...
s, especially the
C preprocessor
The C preprocessor is the macro preprocessor for the C, Objective-C and C++ computer programming languages. The preprocessor provides the ability for the inclusion of header files, macro expansions, conditional compilation, and line control ...
, whereby a
macro may be declared to accept a varying number of
arguments
An argument is a statement or group of statements called premises intended to determine the degree of truth or acceptability of another statement called conclusion. Arguments can be studied from three main perspectives: the logical, the dialectic ...
.
Variable-argument macros were introduced in 1999 in the ''ISO/IEC 9899:1999'' (
C99
C99 (previously known as C9X) is an informal name for ISO/IEC 9899:1999, a past version of the C programming language standard. It extends the previous version ( C90) with new features for the language and the standard library, and helps impl ...
) revision of the
C language standard, and in 2011 in ''ISO/IEC 14882:2011'' (
C++11
C++11 is a version of the ISO/IEC 14882 standard for the C++ programming language. C++11 replaced the prior version of the C++ standard, called C++03, and was later replaced by C++14. The name follows the tradition of naming language versions by ...
) revision of the
C++
C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
language standard. Support for variadic macros with no arguments was added in
C++20
C++20 is a version of the ISO/IEC 14882 standard for the C++ programming language. C++20 replaced the prior version of the C++ standard, called C++17. The standard was technically finalized by WG21 at the meeting in Prague in February 2020, a ...
and will be added in
C23.
[
]
Declaration syntax
The declaration syntax is similar to that of variadic function
In mathematics and in computer programming, a variadic function is a function of indefinite arity, i.e., one which accepts a variable number of arguments. Support for variadic functions differs widely among programming languages.
The term ''varia ...
s: a sequence of three full stop
The full stop (Commonwealth English), period (North American English), or full point , is a punctuation mark. It is used for several purposes, most often to mark the end of a declarative sentence (as distinguished from a question or exclamation ...
s "" is used to indicate that one or more arguments must be passed. During macro expansion each occurrence of the special identifier in the macro replacement list is replaced by the passed arguments.
Additionally, regular macro arguments may be listed before the ...
, but regular arguments may not be listed after the ...
.
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.
Both the C99
C99 (previously known as C9X) is an informal name for ISO/IEC 9899:1999, a past version of the C programming language standard. It extends the previous version ( C90) with new features for the language and the standard library, and helps impl ...
and C++11
C++11 is a version of the ISO/IEC 14882 standard for the C++ programming language. C++11 replaced the prior version of the C++ standard, called C++03, and was later replaced by C++14. The name follows the tradition of naming language versions by ...
standards require at least one argument, but since C++20
C++20 is a version of the ISO/IEC 14882 standard for the C++ programming language. C++20 replaced the prior version of the C++ standard, called C++17. The standard was technically finalized by WG21 at the meeting in Prague in February 2020, a ...
this limitation has been lifted through the functional macro. The macro is replaced by its argument when arguments are present, and omitted otherwise. Common compilers also permit passing zero arguments before this addition, however.[Variadic Macros – Using the GNU Compiler Collection (GCC)](_blank)
/ref>[Variadic Macros (C++)](_blank)
/ref>
The C preprocessor rules prevent macro names in the argument of from expanding recursively. It is possible to work around this limitation up to an arbitrary fixed number of recursive expansions, however.
/ref>
Support
Several compiler
In computing, a compiler is a computer program that translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primarily used for programs that ...
s support variable-argument macros when compiling C and C++ code: the GNU Compiler Collection
The GNU Compiler Collection (GCC) is an optimizing compiler produced by the GNU Project supporting various programming languages, hardware architectures and operating systems. The Free Software Foundation (FSF) distributes GCC as free software ...
3.0, Clang
Clang is a compiler front end for the C, C++, Objective-C, and Objective-C++ programming languages, as well as the OpenMP, OpenCL, RenderScript, CUDA, and HIP frameworks. It acts as a drop-in replacement for the GNU Compiler Collection (GCC), ...
(all versions), Visual Studio 2005
Visual Studio is an integrated development environment (IDE) from Microsoft. It is used to develop computer programs including websites, web apps, web services and mobile apps. Visual Studio uses Microsoft software development platforms such ...
, C++Builder
C++Builder is a rapid application development (RAD) environment, originally developed by Borland and owned by Embarcadero Technologies (a subsidiary of Idera Software, Idera), for writing programs in the C++ programming language currently targeti ...
2006, and Oracle Solaris Studio
Oracle Developer Studio, formerly named Oracle Solaris Studio, Sun Studio, Sun WorkShop, Forte Developer, and SunPro Compilers, is Oracle Corporation's flagship software development product for the Solaris and Linux operating systems. It inclu ...
(formerly Sun Studio) Forte Developer 6 update 2 (C++ version 5.3). GCC also supports such macros when compiling Objective-C
Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXTS ...
.
Support for the macro to support zero arguments has been added in GNU Compiler Collection
The GNU Compiler Collection (GCC) is an optimizing compiler produced by the GNU Project supporting various programming languages, hardware architectures and operating systems. The Free Software Foundation (FSF) distributes GCC as free software ...
8, Clang
Clang is a compiler front end for the C, C++, Objective-C, and Objective-C++ programming languages, as well as the OpenMP, OpenCL, RenderScript, CUDA, and HIP frameworks. It acts as a drop-in replacement for the GNU Compiler Collection (GCC), ...
6, and Visual Studio 2019
Visual Studio is an integrated development environment (IDE) from Microsoft. It is used to develop computer programs including websites, web apps, web services and mobile apps. Visual Studio uses Microsoft software development platforms such ...
.
Example
If a printf
The printf format string is a control parameter used by a class of functions in the input/output libraries of C and many other programming languages. The string is written in a simple template language: characters are usually copied literal ...
-like function
Function or functionality may refer to:
Computing
* Function key, a type of key on computer keyboards
* Function model, a structured representation of processes in a system
* Function object or functor or functionoid, a concept of object-oriente ...
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__)
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
The printf format string is a control parameter used by a class of functions in the input/output libraries of C and many other programming languages. The string is written in a simple template language: characters are usually copied literal ...
is not directly possible. The standard workaround is to use the stdargs functionality of C/C++, and have the function call vprintf
The C programming language provides many standard library functions for file input and output. These functions make up the bulk of the C standard library header . The functionality descends from a "portable I/O package" written by Mike Lesk ...
instead.
Trailing comma
There is a portability issue with generating a trailing comma with empty args for variadic macros in C99
C99 (previously known as C9X) is an informal name for ISO/IEC 9899:1999, a past version of the C programming language standard. It extends the previous version ( C90) with new features for the language and the standard library, and helps impl ...
. Some compilers (e.g., Visual Studio when not using the new standard-conformant preprocessor) will silently eliminate the trailing comma. Other compilers (e.g.: GCC) support putting in front of .
# 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 is empty.
C23 solves this problem by introducing ''__VA_OPT__'' like C++.
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 function:
#define dbgprintf(x) realdbgprintf x
could then be called as:
dbgprintf (("Hello, world %d", 27));
which expands to:
realdbgprintf ("Hello, world %d", 27);
References
{{Reflist
See also
* Variadic function
In mathematics and in computer programming, a variadic function is a function of indefinite arity, i.e., one which accepts a variable number of arguments. Support for variadic functions differs widely among programming languages.
The term ''varia ...
* Variadic template In computer programming, variadic templates are templates that take a variable number of arguments.
Variadic templates are supported by C++ (since the C++11 standard), and the D programming language.
C++
The variadic template feature of C++ was d ...
C (programming language)
C++
ja:可変長引数