匿名结构和联合在 C11 中何时有用? [英] When are anonymous structs and unions useful in 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.
推荐答案
结构内部的匿名联合在实践中非常有用.考虑到您想要实现一个可区分的和类型(或 tagged union),一个带有布尔值的聚合和一个浮点数或一个 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
来实现
The SBCL implementation of Common Lisp does use some union
to implement tagged union types. And GNU make also uses them.
这篇关于匿名结构和联合在 C11 中何时有用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!