打印
[ZLG-ARM]

电容充放电怎么计算

[复制链接]
929|1
手机看帖
扫描二维码
随时随地手机跟帖
沙发
bit6019| | 2011-9-28 00:36 | 只看该作者
下面这段程序是一个C语言的小技巧,其展示了如何把一个参数为结构体的函数转成一个可变参数的函数,其中用到了宏和内建宏“__VA_ARGS__”,下面这段程序可以在GCC下正常编译通过:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#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稀奇古怪的用法。 如果你把宏展开后,你就明的为什么了。下面是宏展开的样子:
1
2
3
4
5
myfunc((struct
mystru){"three", 3});
myfunc((struct
mystru){"hello"});
myfunc((struct
mystru){.name =
"zero"});
myfunc((struct
mystru){.

使用特权

评论回复
发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

个人签名:http://yiguibugui.taobao.com/

315

主题

1645

帖子

4

粉丝