用C联盟的例子 [英] Examples of Union in C
问题描述
我在找一些工会的例子,而不是了解工会工作,我希望我做的,但是看到哪种黑客的人与工会做的。
I'm looking for some union examples, not to understand how union works, hopefully I do, but to see which kind of hack people do with union.
所以,随时分享你的工会破解(当然,:)一些解释)
So feel free to share your union hack (with some explanation of course :) )
推荐答案
一个典型就是要重新present未知类型的值,如一个简单的虚拟机的核心是:
One classic is to represent a value of "unknown" type, as in the core of a simplistic virtual machine:
typedef enum { INTEGER, STRING, REAL, POINTER } Type;
typedef struct
{
Type type;
union {
int integer;
char *string;
float real;
void *pointer;
} x;
} Value;
使用这个你可以写code处理价值不知道他们的确切类型,例如实现堆栈等。
Using this you can write code that handles "values" without knowing their exact type, for instance implement a stack and so on.
由于这是(老,pre-C11)C,内部工会必须在外部给定的字段名称结构
。在C ++中,你可以让联盟
是匿名的。采摘这个名字能吃苦耐劳。我倾向于一些单字母,要因为它几乎从不单独引用,因此它总是从上下文中正在发生的事情不清楚。
Since this is in (old, pre-C11) C, the inner union must be given a field name in the outer struct
. In C++ you can let the union
be anonymous. Picking this name can be hard. I tend to go with something single-lettered, since it is almost never referenced in isolation and thus it is always clear from context what is going on.
code的值设置为一个整数,可能是这样的:
Code to set a value to an integer might look like this:
Value value_new_integer(int v)
{
Value v;
v.type = INTEGER;
v.x.integer = v;
return v;
}
下面我用一个事实,即结构
s时,可以直接返回,处理几乎像一个原始类型的值(可分配结构
S)。
Here I use the fact that struct
s can be returned directly, and treated almost like values of a primitive type (you can assign struct
s).
这篇关于用C联盟的例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!