写过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
本文介绍如何在C语言中使用malloc创建struct的同时初始化成员变量,借助GCC的扩展特性和C99的语法,可以实现一行代码完成这个任务。通过示例代码展示具体操作,并引用了相关StackOverflow问题的链接以供参考。
7063

被折叠的 条评论
为什么被折叠?



