C技巧:结构体参数转成不定参数

本文介绍了一种使用宏将固定结构体参数转换为可变参数的方法,并提供了具体的C语言实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下面这段程序是一个C语言的小技巧,其展示了如何把一个参数为结构体的函数转成一个可变参数的函数,其中用到了宏和内建宏“__VA_ARGS__”,下面这段程序可以在GCC下正常编译通过:

#include <stdio.h> #define func(...) myfunc((struct mystru){__VA_ARGS__}) struct mystru { const char *name; int number; }; void myfunc(struct mystru ms ) { printf("%s: %d/n", ms.name ?: "untitled", ms.number); } int main(int argc, char **argv) { func("three", 3); func("hello"); func(.name = "zero"); func(.number = argc, .name = "argc",); func(.number = 42); return 0; }

 

从上面这段程序,我们可以看到一个叫 myfunc的函数,被func的宏改变了,本来myfunc需要的是一个叫mystru的结构,然而通过宏,我们把struct mystru的这个参数,变成了不定参数列表的一个函数。上面这段程序输出入下,

 

 

three: 3
hello: 0
zero: 0
argc: 1
untitled: 42

 

虽然,这样的用法并不好,但是你可以从另外一个方面了解一下这世上对C稀奇古怪的用法。 如果你把宏展开后,你就明的为什么了。下面是宏展开的样子:

myfunc((struct mystru){"three", 3}); myfunc((struct mystru){"hello"}); myfunc((struct mystru){.name = "zero"}); myfunc((struct mystru){.number = argc, .name = "argc",}); myfunc((struct mystru){.number = 42});

转载于:https://www.cnblogs.com/pang123hui/archive/2010/08/16/2309972.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值