jcf
jcf

Reputation: 602

I don't understand the behavior of this C code (union with 2 bit-field structs, a word and a byte array)

I have the following piece of code in C:

typedef union _REG_CiFIFOCON {
    struct {
        uint32_t RxNotEmptyIE : 1;
        uint32_t RxHalfFullIE : 1;
        uint32_t RxFullIE : 1;
        uint32_t RxOverFlowIE : 1;
        uint32_t unimplemented1 : 1;
        uint32_t RxTimeStampEnable : 1;
        uint32_t unimplemented2 : 1;
        uint32_t TxEnable : 1;
        uint32_t UINC : 1;
        uint32_t unimplemented3 : 1;
        uint32_t FRESET : 1;
        uint32_t unimplemented4 : 13;
        uint32_t FifoSize : 5;
        uint32_t PayLoadSize : 3;
    } rxBF;

    struct {
        uint32_t TxNotFullIE : 1;
        uint32_t TxHalfFullIE : 1;
        uint32_t TxEmptyIE : 1;
        uint32_t unimplemented1 : 1;
        uint32_t TxAttemptIE : 1;
        uint32_t unimplemented2 : 1;
        uint32_t RTREnable : 1;
        uint32_t TxEnable : 1;
        uint32_t UINC : 1;
        uint32_t TxRequest : 1;
        uint32_t FRESET : 1;
        uint32_t unimplemented3 : 5;
        uint32_t TxPriority : 5;
        uint32_t TxAttempts : 2;
        uint32_t unimplemented4 : 1;
        uint32_t FifoSize : 5;
        uint32_t PayLoadSize : 3;
    } txBF;
    uint32_t word;
    uint8_t byte[4];
} REG_CiFIFOCON;

Both structs are 32 bit, so it is the word variable and the byte array (as this is composed of 4 bytes. 4x8 = 32 bits).

My problem is: I don't understand the behavior of this union. I know how to access the bits in each struct and both the word and the array, but how are they related? I know that if there was only 1 struct and the word, setting the word to some value would modify accordingly the bit fields (and viceversa), but I don't know what happens in this case.

Thank you and have a nice day!

Upvotes: 0

Views: 153

Answers (1)

Igal S.
Igal S.

Reputation: 14534

You have 4 types in the same union. All of them are using the same memory.

It doesn't matter which one of them you change - it will affect the others.

The size of your type is 32 bytes - which in your case is also the size of every type inside it. Otherwise - it will be the size of the largest type inside.

Upvotes: 1

Related Questions