我们知道我们可以在C函数中使用可变长度参数。为此,我们必须使用省略号(...)。类似地,对于宏,我们可以使用可变长度参数。这里我们还必须包含省略号,“ __ VA_ARGS__”用于处理可变长度参数。串联运算符“ ##”用于串联变量参数。
在此示例中,宏将采用可变长度参数,例如printf()
orscanf()
函数。在此宏中,我们将打印文件名,行号和错误消息。第一个参数是pr。这用于确定优先级,即是正常信息字符串还是错误
#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" \n", \ 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