什么是匿名结构和联合在C11有用吗? [英] What are anonymous structs and unions useful for in C11?

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

问题描述

C11补充说,除其他事项外,匿名结构和联合。

C11 adds, among other things, 'Anonymous Structs and Unions'.

我戳左右,但找不到的时候匿名结构和联合将是有益的一个明确的解释。我问,因为我不完全理解它们是什么。我得到的,他们是结构或联合之后没有名字,但我一直(只好?)可以把它看成一个错误,所以我只能想象一个使用名为结构。

I poked around but could not find a clear explanation of when anonymous structs and unions would be useful. I ask because I don't completely understand what they are. I get that they are structs or unions without the name afterwards, but I have always (had to?) treat that as an error so I can only conceive a use for named structs.

推荐答案

匿名工会在实践中是非常有用的。想想看,要实现一个歧视总和类型(或标签联合),用布尔以及一个浮动或聚合一个的char * (即一个字符串),这取决于布尔标志。随着C11,你应该能够code

Anonymous union inside structures are very useful in practice. Consider that you want to implement a discriminated sum type (or tagged union), an aggregate with a boolean and either a float or a char* (i.e. a string), depending upon the boolean flag. With C11 you should be able to code

typedef struct {
    bool is_float;
    union {
       float f;
       char* s;
    };
} mychoice_t;

double as_float(mychoice_t* ch) 
{ 
   if (ch->is_float) return ch->f;
   else return atof(ch->s);
}

通过C99,你必须命名工会和code CH-> UF CH->美国这是少可读性和更详细。

With C99, you'll have to name the union, and code ch->u.f and ch->u.s which is less readable and more verbose.

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

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