Chinaunix首页 | 论坛 | 博客
  • 博客访问: 5707784
  • 博文数量: 675
  • 博客积分: 20301
  • 博客等级: 上将
  • 技术积分: 7671
  • 用 户 组: 普通用户
  • 注册时间: 2005-12-31 16:15
文章分类

全部博文(675)

文章存档

2012年(1)

2011年(20)

2010年(14)

2009年(63)

2008年(118)

2007年(141)

2006年(318)

分类: C/C++

2008-04-25 14:25:15

同事在看MFC代码的时候发现的:
#include

struct a
{
        union
        {
                int offset_global;
                struct
                {
                        int offset_part1:31; /*低位*/
                        int offset_part2:1; /*高位*/
                };
        };
        int b;
};

int main()
{
        struct a test;

        test.b = 1;
        test.offset_global = 1;
        printf("%d %d\n", test.offset_part1, test.offset_part2);

        return 0;
}

注意上面的union和union里面的struct的后面都没有像通常的一样加上名字,也就是匿名声明。虽然是匿名声明,还是可以通过直接引用名字来引用到。

实际上,完全可以使用有名声明,只是在写代码的时候要多敲一些代码。
#include

struct a
{
        union u1
        {
                int offset_global;
                struct
                {
                        int offset_part1:31; /*低位*/
                        int offset_part2:1; /*高位*/
                };
        } offset;
        int b;
};

int main()
{
        struct a test;

        test.b = 1;
        test.offset.offset_global = 1;
        printf("%d %d\n", test.offset.offset_part1, test.offset.offset_part2);

        return 0;
}

两段代码的功能是一样的。

union将一个匿名struct和int放在一起是为了方便将int进行拆分。

阅读(3802) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~