简体   繁体   English

如何在运行时区分 c 中的联合成员

[英]how to Distinguish between members of union in c at runtime

I have a doubt regarding unions.我对工会有疑问。 Suppose there is a union defined as假设有一个联合定义为

union emp{
    float f;
    int i;
};

Is there a way to determine which field of union is used.有没有办法确定使用哪个联合字段。 I have come across a situation in which I have to print float if float field is used and print int if int field is used.The function may be like我遇到过这样一种情况,如果使用 float 字段我必须打印 float,如果使用 int 字段则打印 int。function 可能像

void print(union u){

    // if float field is initialized
    printf("float field = %f\n",u.f);

    // if int field is initialized
    printf("int field = %d\n",u.i);


}

Thanks in advance.提前致谢。

You can't tell with just the union ;你不能只用union来判断; typically you wrap it in a struct which includes a tag value of some kind.通常你将它包装在一个包含某种标签值的struct中。

struct val {
  enum { EMP_INT, EMP_FLOAT } tag;
  union emp {
    int i;
    float f;
  } emp;
};

Not really, depending on which field you access the memory will be interpreted as either a float or an int .并非如此,根据您访问的字段, memory 将被解释为floatint

You best choice would be to make the union part of a struct and also keep a flag indicating which field is used.您最好的选择是使联合成为结构的一部分,并保留一个标志来指示使用哪个字段。

You can't, the information isn't stored anywhere at runtime.你不能,信息不会在运行时存储在任何地方。

You could do something like:你可以这样做:

struct emp {
        enum storedValue type;
        union {
                float f;
                int   i;
        }
};

to manually store the type.手动存储类型。 The enum then has values like floatval and intval or similiar.枚举然后具有像floatvalintval或类似的值。

Instead of an enum, you could use a boolean like isFloat .您可以使用 boolean 来代替枚举,例如isFloat

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM