什么是用C无名结构/联合的好处? [英] What are the benefits of unnamed structs / unions in C?

查看:343
本文介绍了什么是用C无名结构/联合的好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了一个code实现如下图所示的类似的演示。

I found one code implemented as the similar demo shown below ..

struct st
{
 int a;
 struct
 {
 int b;
 };
};

6.58内未命名结构/联合字段结构/联合

由于允许通过 ISO C11

但它有什么好处呢?

由于反正我可以访问数据成员像一个相同的方式

Because anyway I can access the data members in a same manner like

int main()
{
 struct st s;
 s.a=11;
 s.b=22;
 return 0;
}

编译海合会4.5.2,

compiled on gcc 4.5.2 with ,

gcc -Wall demo.c -o demo 

和没有错误,

推荐答案

这并不一定是一个结构,我不认为非常有用内的匿名结构:这通常只有引入更多的填充改变布局略有,没有其他明显的影响(与子结构的成员内联到父结构)。

It does not have to be an anonymous struct inside a struct, which I do not find very useful: this will typically only change the layout slightly by introducing more padding, with no other visible effects (compared to inlining the members of the child struct into the parent struct).

我觉得匿名结构/联合的优势是其他地方:
它们可以被用来将一个工会内的匿名结构或匿名联合的结构中。

I think that the advantage of anonymous struct/unions is elsewhere: they can be used to place an anonymous struct inside an union or an anonymous union inside a struct.

例如:

union u
{
  int i;
  struct { char b1; char b2; char b3; char b4; };
};

这篇关于什么是用C无名结构/联合的好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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