ITPub博客

首页 > 应用开发 > C/C++ > C技巧:结构体参数转成不定参数

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

原创 C/C++ 作者:freebus 时间:2020-03-17 13:38:08 0 删除 编辑

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



1#include <stdio.h>

2

3#define func(...) myfunc((struct mystru){__VA_ARGS__})

4 

5struct mystru { const char *name; int number; };

6 

7void myfunc(struct mystru ms )

8{

9  printf("%s: %d\n", ms.name ?: "untitled", ms.number);

10}

11 

12int main(int argc, char **argv)

13{

14  func("three", 3);

15  func("hello");

16  func(.name = "zero");

17  func(.number = argc, .name = "argc",);

18  func(.number = 42);

19  return 0;

20}

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



three: 3

hello: 0

zero: 0

argc: 1

untitled: 42


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


1myfunc((struct mystru){"three", 3});

2myfunc((struct mystru){"hello"});

3myfunc((struct mystru){.name = "zero"});

4myfunc((struct mystru){.number = argc, .name = "argc",});

5myfunc((struct mystru){.number = 42});


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/31365439/viewspace-2680878/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: TWITTER的禁用口令
请登录后发表评论 登录
全部评论

注册时间:2016-06-22

  • 博文量
    34
  • 访问量
    19637