返回匿名结构的函数

问题描述 投票:0回答:1

为什么以下构造无效:

struct { int a, b; float c; } func ()
{
    struct { int a, b; float c; } test;
    
    return test;
    //return (struct { int a, b; float c; }){0,0,0.0}; /* same with designated initializer */
}

它不能用 GCC 编译,出现这个无意义的错误:

错误:返回类型“struct”但返回“struct”时类型不兼容 是预料之中的

警告:控制到达非 void 函数的末尾

c function gcc data-structures compiler-errors
1个回答
0
投票

struct { struct-declaration-list }
的每个实例都定义一个新类型,根据 C 2018 6.7.2.1 8:

结构或联合说明符中结构声明列表的存在声明了翻译单元内的新类型……

这样做的一个原因是我们可能希望将具有相同类型内容的两种结构用于不同的目的。例如,具有两个

float
成员的结构可用于平面中的点,而具有两个
float
成员的另一个结构可用于复数。

由于

func
的声明和
test
的声明都有自己的结构定义,因此它们是不同的类型。不同的结构类型是不兼容的。这就是编译器在
return
语句上发出错误的原因。

要解决此问题,请为结构类型命名,例如:

typedef struct { int a, b; float c; } MyType;

MyType func(void)
{
    MyType test = { 0, 1, 2 };
    return test;
}

或者给结构一个标签:

struct MyTag { int a, b; float c; } func(void)
{
    struct MyTag test = { 0, 1, 2 };
    return test;
}
© www.soinside.com 2019 - 2024. All rights reserved.