c - 如何在 C 中返回匿名结构?

标签 c struct return-value c99 return-type

尝试一些代码,我意识到以下代码可以编译:

struct { int x, y; } foo(void) {
}

似乎我们正在定义一个名为 foo 的函数,它返回一个匿名的 struct

它只是碰巧用我的编译器编译还是这个合法的 C(99)?

如果是这样,return 语句的正确语法是什么?如何将返回值正确分配给变量?

最佳答案

您返回的结构不是匿名结构。 C 标准将匿名结构定义为另一个不使用标记的结构的成员。您返回的是一个没有标签的结构,但由于它不是成员,所以它不是匿名的。 GCC 使用名称 来指示没有标签的结构。

假设您尝试在函数中声明一个相同的结构。

struct { int x, y; } foo( void )
{
    return ( struct { int x, y; } ){ 0 } ;
}

GCC 对此提示:返回类型“struct ”时类型不兼容,但预期为“struct

显然类型不兼容。在标准中我们看到:

6.2.7 Compatible type and composite type

1: Two types have compatible type if their types are the same. Additional rules for determining whether two types are compatible are described in 6.7.2 for type specifiers, in 6.7.3 for type qualifiers, and in 6.7.6 for declarators. Moreover, two structure, union, or enumerated types declared in separate translation units are compatible if their tags and members satisfy the following requirements: If one is declared with a tag, the other shall be declared with the same tag. If both are completed anywhere within their respective translation units, then the following additional requirements apply: there shall be a one-to-one correspondence between their members such that each pair of corresponding members are declared with compatible types; if one member of the pair is declared with an alignment specifier, the other is declared with an equivalent alignment specifier; and if one member of the pair is declared with a name, the other is declared with the same name. For two structures, corresponding members shall be declared in the same order. For two structures or unions, corresponding bit-fields shall have the same widths. For two enumerations, corresponding members shall have the same values.

第二个粗体部分解释了如果两个结构都没有标签,例如在这个例子中,它们必须遵循该部分后面列出的附加要求,它们确实这样做了。但是如果你注意到第一个粗体部分,它们必须在单独的翻译单元中,而示例中的结构不是。所以它们不兼容,代码无效。

要使代码正确是不可能的,因为如果您声明一个结构并在此函数中使用它。您必须使用标签,这违反了两个结构必须具有相同标签的规则:

struct t { int x, y; } ;

struct { int x, y; } foo( void )
{
    struct t var = { 0 } ;

    return var ;
}

GCC 再次提示:当返回类型“struct t”但预期为“struct ”时类型不兼容

关于c - 如何在 C 中返回匿名结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27858240/

相关文章:

c - while循环,k值不会递增

c - 定义一个结构,其中一个成员指向另一个成员

objective-c - 分解 objective-c 中的 typedef 结构

c - 是否可以引用C中的函数返回值?

c++ - cpp 函数来检索各种数据类型的值

c - 在 BLAS (cuBLAS/CUDA) 中将标量添加到 vector

c - 运行 ntpclient 时出错,阻塞在 recvfrom() 函数和 settimeofday() 返回 -1

javascript - 如何在对象字面量中使用另一个 JS 函数的返回值

c - 在 NULL 表示为 0 的平台上,编译器是否曾为 NULL <= p 生成意外代码

c - 如何正确地将 const char 数组分配给结构?