In C language, variable length parameters of macros

WBOY
Release: 2023-08-27 22:49:06
forward
1306 people have browsed it

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.

Example

#include  #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" 

", \ 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 }

Copy after login

Output

[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
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!