是否可以将一个简单的代码块转换为结构体?

Hád*_*dēs 3 c

考虑以下代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

0, 1
Run Code Online (Sandbox Code Playgroud)

我的问题是这条线(struct test) {.i = 0, .t = 1 }在做什么?

它是否在输入一个代码块来输入struct test?甚至可能吗?

如果没有请告诉我它在做什么,谢谢.

Eri*_*hil 7

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 }
Run Code Online (Sandbox Code Playgroud)

复合文字是没有名称的对象.

在普通的初始化列表中,您只需列出要初始化的对象中的项的值.但是,您也可以使用指定的初始化程序.指定的初始值设定项使用结构成员的名称或数组元素的索引来指定对象的哪个部分被赋予指示值:

{ struct { int a, b, c; }) = { .b = 4, .c = 1, .a = 9 }
(int a[1024]) = { [473] = 1, [978] = -1 }
Run Code Online (Sandbox Code Playgroud)

所以,struct test hello = (struct test) { .i = 0, .t = 1 };我们正在创造struct testi初始化为0,并t初始化为1.然后这个struct test是用来初始化另一个名为结构测试hello.

这种特殊用途毫无意义,因为它创造了一个临时对象,以达到可以直接完成的目的.名义上,它创建一个临时的struct test,初始化然后复制到struct test hello.然后临时struct test没有进一步的使用.效果与简单写作相同struct test hello = { .i = 0, .t = 1};.初始化时hello不使用临时对象.但是,一个好的编译器会将它们优化为相同的代码.