Is it valid to use bit fields with union?

前端 未结 2 1379
别那么骄傲
别那么骄傲 2020-12-17 15:33

I have used bit field with a structure like this,

struct
{
       unsigned int is_static: 1;
       unsigned int is_extern: 1;
       unsigned int is_auto: 1         


        
2条回答
  •  南方客
    南方客 (楼主)
    2020-12-17 16:27

    You are given a gun and bullets. Is it okay to shoot your self in foot with it? Of course not, but nobody can stop you from doing this if you want to.

    My point is, just like gun and bullets, union and bit fields are tools and they have their purpose, uses and "abuses". So using bitfields in union, as you have written above, is perfectly valid C but a useless piece of code. All the fields inside union share same memory so all the bitfields you mention are essentially same flag as they share same memory.

提交回复
热议问题