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

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

问题描述

我发现一个代码实现为如下所示的类似演示..

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

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

6.58 structs/unions

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;
}

在 gcc 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天全站免登陆