使用union时可以使用union实现相同的优点

Nav*_*K N 6 c struct unions data-structures

我很难理解unionC中的使用.我在这里读了很多关于这个主题的帖子.但是,union当使用结构可以实现同样的事情时,他们都没有解释为什么是首选.

引用K&R

作为可能在编译器符号表管理器中找到的示例,假设常量可以是int,float或字符指针.特定常量的值必须存储在适当类型的变量中,但如果值占用相同的存储量并且存储在同一位置(无论其类型如何),则最方便表管理.这是一个联合的目的,一个变量可以合法地保存几种类型中的任何一种.语法基于结构:

union u_tag {
      int ival;
      float fval;
      char *sval;
} u;
Run Code Online (Sandbox Code Playgroud)

用法将是

if (utype == INT)
    printf("%d\n", u.ival);
if (utype == FLOAT)
    printf("%f\n", u.fval);
if (utype == STRING)
    printf("%s\n", u.sval);
else
    printf("bad type %d in utype\n", utype);
Run Code Online (Sandbox Code Playgroud)

使用结构可以实现相同的功能.就像是,

struct u_tag {
    utype_t utype;
    int ival;
    float fval;
    char *sval;
} u;

if (u.utype == INT)
    printf("%d\n", u.ival);
if (u.utype == FLOAT)
    printf("%f\n", u.fval);
if (u.utype == STRING)
    printf("%s\n", u.sval);
else
    printf("bad type %d in utype\n", utype);
Run Code Online (Sandbox Code Playgroud)

这不一样吗?有什么好处union

有什么想法吗?

Ama*_*osh 9

在您发布的示例中,union的大小将是float的大小(假设它是最大的 - 如注释中所指出的,它可以在64位编译器中变化),而struct的大小将是总和float,int,char*和utype_t(以及填充,如果有的话)的大小.

我的编译器上的结果:

union u_tag {
    int ival;
    float fval;
    char *sval;
};
struct s_tag {
    int ival;
    float fval;
    char *sval;
};

int main()
{
    printf("%d\n", sizeof(union u_tag));  //prints 4
    printf("%d\n", sizeof(struct s_tag)); //prints 12
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • @Appu - 没有它们根本不同,一个struct分别存储所有的值.union允许您将单个内存位置称为int/float/long等. (6认同)

Mic*_*kis 8

当一次只需要访问一个成员时,可以使用联合.这样,您可以节省一些内存而不是使用结构.

工会可能有一个整洁的"作弊":写一个字段并从另一个字段读取,检查位模式或以不同方式解释它们.