C技巧:结构体参数转成不定参数
下面这段程序是一个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});
转载于酷壳CoolShell 无删改 仅以此纪念陈皓(左耳朵耗子)
在编码领域,哪些大模型的能力比较强?目前一直都在用 claude-3.7-sonnet 那显然 chatgpt 感觉是 claude-3.7-sonnet 和 gemi…
昨天看到 V 友发的主题 ddl.ink/AiSv 有没有大佬知道两者有什么区别,有没有坑 以前买过同配置 CVM 主机 3 年要 688 ,能不能用轻量云主机替代 …
昨天下午 直接一个短信通知 告诉我把我的服务器封了,说我涉黄了 服务器就我自己在用,哪有那些东西😂 找客服 找了两个小时 一直是等核实 等核实 等核实 核实了一晚上没消息 今…
合速度