分享

union深度探索

 lhzstudio 2012-05-11
typdef union {
       int n;
       char c;
} NC;

nc.c   确实有 *(char *)&nc   的意思
nc.n 确实有 *(int *)&nc     的意思
(存取方式)

我觉得,可以用union去描述同一概念,但不会同时出现的东西。
比如
union mark
{
int score;
char grade;
}

写程序时,别人比较容易理解;改的时候也容易。

The primary usefulness of a union is to conserve space, since it provides a way of letting many different types be stored in the same space. Unions also provide crude polymorphism. However, there is no checking of types, so it is up to the programmer to be sure that the proper fields are accessed in different contexts. The relevant field of a union variable is typically determined by the state of other variables, possibly in an enclosing struct.
(union常不是单独使用,而是与struct一起,它的值常是由密封在struct中的其他变量的状态决定的)


举个例子:
[php]
struct in6_addr
   {
union
   {
       uint8_t u6_addr8[16];
       uint16_t u6_addr16[8];
       uint32_t u6_addr32[4];
   } in6_u;
#define s6_addr                 in6_u.u6_addr8
#define s6_addr16             in6_u.u6_addr16
#define s6_addr32             in6_u.u6_addr32
   };
[/php]

uinion在协议里用的很多

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多