我很难理解C中联合的使用.我在这里读了很多关于这个主题的帖子.但是,当使用结构可以实现同样的事情时,他们都没有解释为什么联合是首选的.
引自K& R.
As an example such as might be found
in a compiler symbol table manager,
suppose that a constant may be an int,
a float,or a character pointer. The
value of a particular constant must be
stored in a variable of the proper
type,yet it is most convenient for
table management if the value occupies
the same amount of storage and is
stored in the same place regardless of
its type. This is the purpose of a
union a single variable that can
legitimately hold any of one of
several types. The Syntax is based on
structures:
union u_tag { int ival; float fval; char *sval; } u;
用法将是
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);
使用结构可以实现相同的功能.就像是,
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",utype);
这不一样吗?联盟给了什么优势?
有什么想法吗?
解决方法
在您发布的示例中,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; }