使用标签C结构的初始化。它的工作原理,但如何?文档? [英] C struct initialization using labels. It works, but how? Documentation?

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

问题描述

昨天我发现了一些结构的初始化code抛出我要循环。这里有一个例子:

  typedef结构{诠释第一;诠释秒; } TEST_STRUCT;
无效testFunc(){
    TEST_STRUCT测试= {
    第二:2,
    第一:1
    };
    的printf(test.first =%d个test.second =%d个\\ N,test.first,test.second);
}

令人惊讶的(对我来说),这里是输出:

   - > testFunc
test.first = 1 test.second = 2

正如你所看到的,结构得到正确初始化。我是不是可以用来了解标号语句这样。我见过做初始化结构等几种方式,但我没有找到任何关于网上的C常见问题的这种结构初始化的任何实例。是任何人知道如何/为什么这样的作品?或文件说明它是正确的语法?


解决方案

下面是GCC手册的这解释为结构和数组初始化指定的语法部分:


  

在结构初始化,指定一个字段的名称来初始化
  与 .fieldname = 的'之前的元素值。例如,给定的
  以下结构,

 结构点{INT X,Y; };


  
  

以下初始化

 结构点p = {.Y = y值,.X = xvalue};


  
  

等同于

 结构点p = {xvalue,y值};


  
  

具有相同的意义,因为GCC 2.5过时的另一种语法,就是'的字段名:的',如下所示:

 结构点p = {Y:y值,X:xvalue};


相关页面,可以发现<一个href=\"http://gcc.gnu.org/onlinedocs/gcc-4.4.1/gcc/Designated-Inits.html#Designated-Inits\">here.

您的编译器应该有类似的文档。

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

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?

解决方案

Here is the section of the gcc manual which explains the syntax of designated initializers for both structs and arrays:

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; };

the following initialization

 struct point p = { .y = yvalue, .x = xvalue }; 

is equivalent to

 struct point p = { xvalue, yvalue }; 

Another syntax which has the same meaning, obsolete since GCC 2.5, is 'fieldname:', as shown here:

 struct point p = { y: yvalue, x: xvalue };

The relevant page can be found here.

Your compiler should have similar documentation.

这篇关于使用标签C结构的初始化。它的工作原理,但如何?文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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