问题描述
我昨天发现了一些结构体初始化代码,这让我陷入了循环.举个例子:
I found some struct initialization code yesterday that threw me for a loop. Here's an example:
typedef struct { int first; int second; } TEST_STRUCT;
void testFunc() {
TEST_STRUCT test = {
second: 2,
first: 1
};
printf("test.first=%d test.second=%d
", test.first, test.second);
}
令人惊讶的是(对我而言),这是输出:
Surprisingly (to me), here's the output:
-> testFunc
test.first=1 test.second=2
如您所见,该结构已正确初始化.我不知道可以这样使用带标签的语句.我已经看到了其他几种进行结构体初始化的方法,但是我没有在任何在线 C 常见问题解答中找到这种结构体初始化的任何示例.有人知道这是如何/为什么工作的吗?
As you can see, the struct gets initialized properly. I wasn't aware labeled statements could be used like that. I've seen several other ways of doing struct initialization, but I didn't find any examples of this sort of struct initialization on any of the online C FAQs. Is anybody aware of how/why this works?
推荐答案
这里是 gcc 手册的一节,解释了结构和数组的指定初始值设定项的语法:
Here is the section of the gcc manual which explains the syntax of designated initializers for both structs and arrays:
在结构初始化器中,指定要初始化的字段的名称'.fieldname =' 在元素值之前.例如,给定以下结构,
struct point { int x, y; };
下面的初始化
struct point p = { .y = yvalue, .x = xvalue };
相当于
struct point p = { xvalue, yvalue };
另一种具有相同含义的语法(自 GCC 2.5 起已过时)是fieldname:",如下所示:
Another syntax which has the same meaning, obsolete since GCC 2.5, is 'fieldname:', as shown here:
struct point p = { y: yvalue, x: xvalue };
相关页面可以找到这里.
你的编译器应该有类似的文档.
Your compiler should have similar documentation.
这篇关于使用标签的 C 结构初始化.它有效,但如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!