Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
757 views
in Technique[技术] by (71.8m points)

c - Is it valid to use bit fields with union?

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;
} flags;

Now i wondered to see if this can be done with a union so i modified the code like,

union
{
       unsigned int is_static: 1;
       unsigned int is_extern: 1;
       unsigned int is_auto: 1;
} flags;

I found the bit field with union works but all those fields in the union are given to a single bit as I understood from output. Now I am seeing it is not erroneous to use bit fields with union, but it seems to me that using it like this is not operationally correct. So what is the answer - is it valid to use bit field with union?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It is valid but as you found out, not useful the way you have done it there.

You might do something like this so you can reset all the bits at the same time using flags.

union {
    struct {
        unsigned int is_static: 1;
        unsigned int is_extern: 1;
        unsigned int is_auto: 1;
    };
    unsigned int flags;
};

Or you might do something like this:

union {
    struct {
        unsigned int is_static: 1;
        unsigned int is_extern: 1;
        unsigned int is_auto: 1;
    };
    struct {
        unsigned int is_ready: 1;
        unsigned int is_done: 1;
        unsigned int is_waiting: 1;
    };
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...