您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

在C语言中,宏的可变长度参数

2024/3/1 4:49:02发布26次查看
我们知道在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
以上就是在c语言中,宏的可变长度参数的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product