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

使用union时可以使用union实现相同的优点,第1张

概述我很难理解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 我很难理解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;}
总结

以上是内存溢出为你收集整理的使用union时可以使用union实现相同的优点全部内容,希望文章能够帮你解决使用union时可以使用union实现相同的优点所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1237902.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存