search

Home  >  Q&A  >  body text

c++ - What is the use of union in C language?

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?

世界只因有你世界只因有你2809 days ago1063

reply all(5)I'll reply

  • 漂亮男人

    漂亮男人2017-06-12 09:26:44

    Save memory and facilitate access to high and low bytes

    reply
    0
  • 某草草

    某草草2017-06-12 09:26:44

    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.

    reply
    0
  • ringa_lee

    ringa_lee2017-06-12 09:26:44

    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.

    reply
    0
  • 女神的闺蜜爱上我

    女神的闺蜜爱上我2017-06-12 09:26:44

    Generally used to determine the big and small ends

    reply
    0
  • 给我你的怀抱

    给我你的怀抱2017-06-12 09:26:44

    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.

    reply
    0
  • Cancelreply