c++ - What is the use of union in C language?
世界只因有你
世界只因有你 2017-06-12 09:24:44
0
5
1042

RT, the last assignment of this structure will overwrite the previous assignment, so I’m curious as to what scenarios this kind of thing is generally used in?

世界只因有你
世界只因有你

reply all(5)
漂亮男人

Save memory and facilitate access to high and low bytes

某草草

The original purpose was to save memory. If you think about it, C language only began to be used on a large scale in the 1980s, and memory was very precious at that time.

左手右手慢动作

Can provide different access interfaces to the same piece of data. . .
For example, when you were doing embedded work, you could write like this:

// 没有字节对齐,或者字节对齐为1,int 占4字节
typedef union {
    unsigined int num;
    struct {
        unsigned char byte0;
        unsigned char byte1;
        unsigned char byte2;
        unsigned char byte3;
    } bytes;
} Demo;

However, it is not very concise to write this way, and the efficiency of this code in PC is the same as directly fetching each byte through bit shifting. Just an example, don't get too hung up on it.

女神的闺蜜爱上我

Generally used to determine the big and small ends

给我你的怀抱

It is often used in embedded development. Let me give an example here, which is similar to @zonxin’s above

typedef struct __regular_descriptor_4_high {
    union {
        U32 value;
        struct {
            U32 raid_id0    : 4;
            U32 raid_cmd0   : 4;
            U32 raid_id1    : 4;
            U32 raid_cmd1   : 4;
            U32 raid_id2    : 4;
            U32 raid_cmd2   : 4;
            U32 raid_id3    : 4;
            U32 raid_cmd3   : 4;
        } reg_des_bit;   
    } u; 
} reg_des_4_high;

To read the entire register, you can read value. To write different bit-filed, use reg_des_bit to write.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template