我可以检查c中的union是否为空?例如:
union{ char * name, struct Something * something ... }someUnion;
有没有办法检查是否没有元素被初始化,而没有进行元素虎钳检查?
感谢。
答案 0 :(得分:6)
不,不是没有为此目的添加特定标志。例如:
struct someStruct {
int initialized;
union {
char *name;
struct Something *something;
};
};
您甚至可以存储一个标志而不是initialized
来指示联合包含哪种数据。这通常称为Tagged union。
答案 1 :(得分:1)
是的,在联合的所有成员都是指针类型或整数类型的条件下,并且初始化意味着已经分配了一个非NULL的值,只需检查一个 NULL的元素。
union {
char * name;
struct Something * something; } someUnion;
if (someUnion.name != 0) {
// here you know that someUnion.something is not NULL too.
// You don't know if it has been initialized as char*
// or as struct something* though. Presumeably since
// it is a unionboth interpretations make some sense.
}