Home > Article > Backend Development > In C language, variable length parameters of macros
We know that functions can be defined using variable length parameters in C language. For this we need to use ellipses (…). Similarly, in macros, we can also use variable length parameters. Here, too, we need to include the ellipses. ‘__VA_ARGS__’ is used to handle variable length arguments. The concatenation operator ‘##’ is used to concatenate variadic parameters.
In this example, the macro will accept variable-length arguments, just like the printf() or scanf() functions. In this macro, we will print the file name, line number, and error message. The first parameter is pr. It is used to determine priority, that is, whether it is a normal message string or an error message.
#include <stdio.h> #define INFO 1 #define ERR 2 #define STD_OUT stdout #define STD_ERR stderr #define LOG_MESSAGE(pr, strm, msg, ...) do {\ char *str;\ if (pr == INFO)\ str = "INFORMATION";\ else if (pr == ERR)\ str = "ERROR";\ fprintf(strm, "[%s] : %s : %d : "msg" </p><p>", \ str, __FILE__, __LINE__, ##__VA_ARGS__);\ } while (0) int main(void) { char *s = "Test String"; LOG_MESSAGE(ERR, STD_ERR, "Unable to open the file"); //here normal message will be printed LOG_MESSAGE(INFO, STD_OUT, "%s is passed as argument", s); //pass string argument LOG_MESSAGE(INFO, STD_OUT, "%d + %d = %d", 14, 16, (14 + 16)); //Provide integer }
[ERROR] : D:\text.c : 21 : Unable to open the file [INFORMATION] : D:\text.c : 23 : Test String is passed as argument [INFORMATION] : D:\text.c : 25 : 14 + 16 = 30
The above is the detailed content of In C language, variable length parameters of macros. For more information, please follow other related articles on the PHP Chinese website!