我可以检查c中的联合是否为空吗?例如:
union{ char * name, struct Something * something ... }someUnion;
有没有办法检查是否没有元素被初始化,而不做元素虎钳检查?
谢谢。
不,不是没有为此目的添加特定标志。例如:
struct someStruct {
int initialized;
union {
char *name;
struct Something *something;
};
};
您甚至可以存储一个标志来代替initialized
指示联合包含哪种数据的标志。这通常称为标记联合。
是的,在联合的所有成员都是指针类型或整数类型的条件下,并且初始化意味着已分配了一个非 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.
}