Macro Parameters ...

This page was translated by a robot.

It is possible to define macros that take a variable number of arguments. These so-called variadic macros are defined with three ellipses , after which the arguments represented by them can be addressed ...in the macro definition with the predefined macro .__VA_ARGS__





The error 99 occured.
#include <stdio.h>
#define PRINT(string, ...) printf(string, __VA_ARGS__)

int main(){
  PRINT("The error %d occured.", 99);
  return 0;
}

Details

It should be noted that not only variadic macros exist in C and C++, but also variadic functions .

The three ellipses are called ellipsis in English . In German, this corresponds to the term ellipse .

__VA_ARGS__You can also give the additional arguments your own name instead of the macro . This feature is only described in C++, but today's compilers also allow this for C files. The naming is achieved by specifying the ellipses of ...the desired names in the parameter list of the macro definition:

#define PRINT(string, args...) printf(string, args)

If a variadic macro is used without the additional arguments, these are unfortunately not automatically omitted, so calling the above macro can lead to a syntax error, as can be seen in the translation of the following line by the preprocessor:


printf("Error!", );
#define PRINT(string, args ...) printf(string, args)
PRINT("Error!");

To avoid this error, GCC provides a special version of the double hash character ##, which causes non-existent arguments of variadic macros to be automatically removed along with the preceding comma (only works with comma!), whereupon the preprocessor correctly interprets the line implements:


printf("Error!");
#define PRINT(string, args ...) printf(string, ## args)
PRINT("Error!");