Jump to content

Variadic macro in the C preprocessor

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Kate (talk | contribs) at 20:26, 10 June 2004. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

A variable argument macro, or varargs macro, is a feature of the C programming language which permits preprocessor macros to accept a varying number of arguments. Their syntax is similar to that of variable argument functions: the special sequence "..." is used to indicate one or more arguments. The identifier __VA_ARGS__ in the macro definition is then substituted by these arguments.

For example, if a printf-like function dprintf() were desired, which would pass the file and line number from which it was called as arguments, the following macro might be used:

void realdprintf (char const *file, int line, char const *fmt, ...); 
#define dprintf(...) realdprintf(__FILE__, __LINE__, __VA_ARGS__);

dprintf() could then be called as:

dprintf("Hello, world");
/* Expands to: 
 *     realdprintf(__FILE__, __LINE__, "Hello, world"); 
 */

or:

dprintf("%d + %d = %d", 2, 2, 5);
/* Expands to: 
 *     realdprintf(__FILE__, __LINE__, "%d + %d = %d", 2, 2, 5);
 */

Variable argument macros are supported in the C language since ISO/IEC 9899:1999, C99.