C 宏的变长参数


我们知道,我们可以在 C 中针对函数使用变长参数。为此,我们必须使用省略号 (…)。同样,对于宏,我们也可以使用变长参数。在这里,我们也必须包括省略号,使用 '__VA_ARGS__' 来处理变长参数。连接运算符 '##' 用于连接可变参数。

在此示例中,宏将获取变长参数,例如 printf() 或 scanf() 函数。在此宏中,我们将打印文件名、行号和错误消息。第一个参数是 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" 
", \       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

更新时间:2019 年 7 月 30 日

884 次浏览

开启您的 职业

通过完成课程进行认证

开始
广告
© . All rights reserved.