[英]Is is possible to cast a simple block of code to a struct?
考虑以下代码:
#include <stdio.h>
int main()
{
struct test {
int i;
int t;
};
struct test hello = (struct test) {
.i = 0,
.t = 1
};
printf("%d, %d\n", hello.i, hello.t);
return 0;
}
输出:
0, 1
我的问题是这一行(struct test) {.i = 0, .t = 1 }
在做什么?
它是否在输入一个代码块来输入struct test? 甚至可能吗?
如果没有请告诉我它在做什么,谢谢。
struct test hello = (struct test) { .i = 0, .t = 1 };
使用C的两个特征,称为复合文字和指定的初始化器 。
复合文字的一般形式是: (
type-name )
{
initializer-list }
。 (列表后面可能还有一个逗号。)例如,这些是复合文字:
(int) { 3 }
(int []) { 0, 1, 2 }
(union { float f; unsigned int u; }) = { 3.4 }
复合文字是没有名称的对象。
在普通的初始化列表中,您只需列出要初始化的对象中的项的值。 但是,您也可以使用指定的初始化程序。 指定的初始值设定项使用结构成员的名称或数组元素的索引来指定对象的哪个部分被赋予指示值:
{ struct { int a, b, c; }) = { .b = 4, .c = 1, .a = 9 }
(int a[1024]) = { [473] = 1, [978] = -1 }
所以,在struct test hello = (struct test) { .i = 0, .t = 1 };
,我们创建struct test
与i
初始化为0,并t
初始化为1。然后这个struct test
被用来初始化另一个名为结构测试hello
。
这种特殊用途毫无意义,因为它创造了一个临时对象,以达到可以直接完成的目的。 名义上,它创建一个临时的struct test
,初始化然后复制到struct test hello
。 然后临时struct test
没有进一步的使用。 效果与简单编写struct test hello = { .i = 0, .t = 1};
。 在不使用临时对象的情况下初始化hello
。 但是,一个好的编译器会将它们优化为相同的代码。
在C(和许多相关的编程语言)中,花括号通常意味着:
{
这是代码开始的地方
}
这是那里的代码结束
它们也可以有几种不同的含义。 它们不仅涉及代码,还涉及数据结构:
struct point {
int x;
int y;
};
在这种情况下,它们定义数据结构的开始和结束位置。
struct point pythagoras = {
.x = 3,
.y = 4
};
在这种情况下,它们定义变量的初始内容的开始和结束位置。
总之, {
表示开始,而}
表示结束。 而已。
初始化struct test
的“代码”不是真正的代码,尽管它看起来真的很像。 这又是:
struct test hello = (struct test) {
.i = 0,
.t = 1
};
通常, (type)
表示类型转换。 但是,在这种情况下, (struct test)
后跟一个左括号{
,这个组合称为复合文字 。 它是复合数据类型变量的文字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.