如何按照 C 编程语言标准初始化结构体 [英] How to initialize a struct in accordance with C programming language standards
问题描述
我想初始化一个结构元素,分为声明和初始化.这就是我所拥有的:
I want to initialize a struct element, split in declaration and initialization. This is what I have:
typedef struct MY_TYPE {
bool flag;
short int value;
double stuff;
} MY_TYPE;
void function(void) {
MY_TYPE a;
...
a = { true, 15, 0.123 }
}
这是按照C编程语言标准(C89、C90、C99、C11等)声明和初始化MY_TYPE
的局部变量的方式吗?或者有什么更好的或至少有效的方法吗?
Is this the way to declare and initialize a local variable of MY_TYPE
in accordance with C programming language standards (C89, C90, C99, C11, etc.)? Or is there anything better or at least working?
更新我最终得到了一个静态初始化元素,我可以根据需要设置每个子元素.
Update I ended up having a static initialization element where I set every subelement according to my needs.
推荐答案
在 (ANSI) C99 中,您可以使用指定的初始化程序来初始化一个结构:
In (ANSI) C99, you can use a designated initializer to initialize a structure:
MY_TYPE a = { .flag = true, .value = 123, .stuff = 0.456 };
其他成员初始化为零:省略的字段成员隐式初始化与具有静态存储持续时间的对象相同."(https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html)
Other members are initialized as zero: "Omitted field members are implicitly initialized the same as objects that have static storage duration." (https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html)
这篇关于如何按照 C 编程语言标准初始化结构体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!