Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio 2005
Visual Studio
Visual C++
Reference
C/C++ Languages
The Preprocessor
Macros
 Variadic Macros
Collapse All/Expand All Collapse All
This page is specific to
Microsoft Visual Studio 2005/.NET Framework 2.0

Other versions are also available for the following:
Visual C++ Language Reference
Variadic Macros

Variadic macros are function-like macros that contain a variable number of arguments.

To use variadic macros, the ellipsis may be specified as the final formal argument in a macro definition, and the replacement identifier __VA_ARGS__ may be used in the definition to insert the extra arguments. __VA_ARGS__ is replaced by all of the arguments that match the ellipsis, including commas between them.

The C Standard specifies that at least one argument must be passed to the ellipsis, to ensure that the macro does not resolve to an expression with a trailing comma. The Visual C++ implementation will suppress a trailing comma if no arguments are passed to the ellipsis.

Support for variadic macros was introduced in Visual C++ 2005.

// variadic_macros.cpp
#include <stdio.h>
#define EMPTY

#define CHECK1(x, ...) if (!(x)) { printf(__VA_ARGS__); }
#define CHECK2(x, ...) if ((x)) { printf(__VA_ARGS__); }
#define CHECK3(...) { printf(__VA_ARGS__); }
#define MACRO(s, ...) printf(s, __VA_ARGS__)

int main() {
   CHECK1(0, "here %s %s %s", "are", "some", "varargs1(1)\n");
   CHECK1(1, "here %s %s %s", "are", "some", "varargs1(2)\n");   // won't print

   CHECK2(0, "here %s %s %s", "are", "some", "varargs2(3)\n");   // won't print
   CHECK2(1, "here %s %s %s", "are", "some", "varargs2(4)\n");

   // always invokes printf in the macro
   CHECK3("here %s %s %s", "are", "some", "varargs3(5)\n");

   MACRO("hello, world\n");
   // MACRO("error\n", EMPTY);   would cause C2059
}

Output

here are some varargs1(1)
here are some varargs2(4)
here are some varargs3(5)
hello, world

Reference

Macros (C/C++)

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
is this hardcoded into the compiler?      Ivo Roper   |   Edit   |   Show History
I had hoped to look at the source for __VA_ARGS__ to modify it slightly, but I can't find it in the source anywhere, yet it works despite that. Is this just a built-in keyword that the compiler implements? This is certainly implied, but I'm curious if there is a macro-based implementation of it out there somewhere.

[moves on to the next task]
Tags What's this?: Add a tag
Flag as ContentBug
Processing
© 2010 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement
Page view tracker