初始化结构而不分配? [英] Initialize struct without an assignment?

查看:74
本文介绍了初始化结构而不分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在Internet上找到答案,所以这是我的问题:是否可以在不将其分配给C中的局部变量或全局变量的情况下定义结构实例?例如:

I could not find an answer to this on the Internet, so here is my question: Can I define a struct instance without assigning it to a local or global variable in C? E.g.:

struct A {
  int b;
}

struct A foo() {
  return struct A { .b = 42 };
}

如果这不可能:为什么?

If this is not possible: why?

推荐答案

是的,C99为此提供了复合文字( 现场直播 ):

Yes C99 provides compound literals for this (see it live):

return (struct A) {  42 } ;

C99草稿标准

which is covered in the draft C99 standard section 6.5.2.5 Compound literals and says:

由括号类型名称和括号括起来的初始化程序列表组成的后缀表达式是复合文字.它提供了一个未命名的对象,其 值由初始值设定项列表给出. 84)

A postfix expression that consists of a parenthesized type name followed by a brace enclosed list of initializers is a compound literal. It provides an unnamed object whose value is given by the initializer list.84)

和:

复合文字的值是由初始化的未命名对象的值. 初始化列表.如果复合文字出现在函数主体之外,则对象 具有静态存储期限;否则,它具有与 封闭的块.

The value of the compound literal is that of an unnamed object initialized by the initializer list. If the compound literal occurs outside the body of a function, the object has static storage duration; otherwise, it has automatic storage duration associated with the enclosing block.

并提供了一些示例,包括:

and provides several examples including:

示例3具有指定名称的初始化程序可以与复合文字结合使用.结构对象 使用复合文字创建的内容可以不依赖于成员顺序而传递给函数:

EXAMPLE 3 Initializers with designations can be combined with compound literals. Structure objects created using compound literals can be passed to functions without depending on member order:

drawline((struct point){.x=1, .y=1}, (struct point){.x=3, .y=4});

gcc还有一个不错的文档在扩展部分中对此进行了介绍,因为它在C99和clang之外都支持此功能.

gcc also has a nice document on this in it's extension section since it supports this feature outside of C99 as well as clang.

这篇关于初始化结构而不分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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