C结构体初始化使用标签。它的作品,但如何?文档? [英] C struct initialization using labels. It works, but how? Documentation?
问题描述
我昨天发现了一些结构化初始化代码,使我陷入了一个循环。这里有一个例子:
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\n", test.first, test.second);
}
令人惊讶的是(对我来说),这里是输出:
Surprisingly (to me), here's the output:
-> testFunc
test.first=1 test.second=2
如你所见, struct得到初始化正确。我不知道标签的声明可以这样使用。我已经看过几种其他的方法来进行结构化初始化,但是我没有在任何在线C常见问题解答中找到这种类型的struct初始化的例子。有人知道如何/为什么这样工作吗?或者文档说明它是正确的语法?
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? Or documentation stating it is correct syntax?
推荐答案
以下是gcc手册的一节,介绍指定的初始化程序的语法结构和数组:
Here is the section of the gcc manual which explains the syntax of designated initializers for both structs and arrays:
在结构初始化器中,指定要用' .fieldname初始化
的字段的名称= '之前的元素值。例如,给定
以下结构,
In a structure initializer, specify the name of a field to initialize with '.fieldname =' before the element value. For example, given the following structure,
struct point { int x, y; };
以下初始化
struct point p = { .y = yvalue, .x = xvalue };
相当于
struct point p = { xvalue, yvalue };
另一种具有相同含义的语法,因为GCC 2.5过时,是' fieldname: / em>',如下所示:
Another syntax which has the same meaning, obsolete since GCC 2.5, is 'fieldname:', as shown here:
struct point p = { y: yvalue, x: xvalue };
相关页面可以找到 here 。
您的编译器应该有类似的文档。
Your compiler should have similar documentation.
这篇关于C结构体初始化使用标签。它的作品,但如何?文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!