C语言malloc创建struct同时初始化成员变量

来源:互联网 发布:黄金投资 知乎 编辑:程序博客网 时间:2024/06/07 21:48

写过C程序都知道,malloc了新的struct之后,经常跟着一大串的赋值\初始化语句。其实这些可以用一行漂亮的代码搞定。

先上代码:

#define new(type, ...) ({\       type* __t = (type*) malloc(sizeof(type));\       *__t = (type){__VA_ARGS__};\       __t; })

使用示例:

struct S {    union {        int x, y;    };    enum {AA, BB} e;};int main() {    struct S *s1 = new(struct S);    struct S *s2 = new(struct S, 12);    struct S *s3 = new(struct S, 12, BB);    struct S *s4 = new(struct S, .e = BB, .x = 12);}

这段代码仅在GCC里work,因为用到了GCC的一个扩展特性,加了括号的block(({ }))可以带有返回值,即最后一个语句的返回值。

还用到了C99的一个feature,就是那个非常酷炫的.field =的赋值。

另外三个点的宏定义,看例子就差不多明白了吧。

Ref.
http://stackoverflow.com/questions/2679182/have-macro-return-a-value
http://stackoverflow.com/questions/3016107/what-is-tagged-structure-initialization-syntax
http://gcc.gnu.org/onlinedocs/cpp/Variadic-Macros.html

0 0
原创粉丝点击