gpt4 book ai didi

c - 在没有赋值的情况下初始化结构?

转载 作者:太空狗 更新时间:2023-10-29 15:35:45 24 4
gpt4 key购买 nike

我在 Internet 上找不到这个问题的答案,所以这是我的问题:我可以定义一个结构实例而不将它分配给 C 中的局部或全局变量吗?例如:

struct A {
int b;
}

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

如果这是不可能的:为什么?

最佳答案

是的,C99 为此提供了复合文字 ( see it live ):

return (struct A) {  42 } ;

draft C99 standard 中涵盖6.5.2.5 Compound literals 部分说:

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.

并提供了几个示例,包括:

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 还有一个 nice document在它的扩展部分中对此进行了说明,因为它在 C99 以及 clang 之外支持此功能。

关于c - 在没有赋值的情况下初始化结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23294769/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com