什么时候在C11中有用匿名结构和联合? [英] When are anonymous structs and unions useful in C11?

查看:70
本文介绍了什么时候在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,您应该可以进行编码

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,您必须命名联合,并为代码 ch-> uf ch-> us 编写代码,这些代码可读性较差,而且比较冗长.

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.

实现某些标记的联合类型的另一种方法是使用强制类型转换. Ocaml运行时提供了很多示例.

Another way to implement some tagged union type is to use casts. The Ocaml runtime gives a lot of examples.

Common Lisp的 SBCL 实现确实使用某些 union 来实现标记为联合类型.并且 GNU make 也使用它们.

The SBCL implementation of Common Lisp does use some union to implement tagged union types. And GNU make also uses them.

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

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