使用标签的C结构初始化.它有效,但是如何? [英] C struct initialization using labels. It works, but how?

查看:66
本文介绍了使用标签的C结构初始化.它有效,但是如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

昨天我找到了一些结构初始化代码,这些代码使我陷入了循环.这是一个示例:

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

如您所见,该结构已正确初始化.我不知道标记的语句可以这样使用.我已经看到了进行结构初始化的其他几种方法,但是在任何在线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 = ".例如,给定 以下结构,

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:',如下所示:

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结构初始化.它有效,但是如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆