c++ - What purpose to use union in struct? -




i'm struggling uart snippet codes embedded uart program.

then came across can't undersatnd when analysing code.

q1. in case of using "union" in "struct". benefit , purpose use this?

#define     __io    volatile     typedef struct {   union {   __io  uint32_t rr;   __io  uint32_t tr;   __io  uint32_t dl;   __io  uint32_t rr_tr_dl;   };   union {   __io  uint32_t dh;   __io  uint32_t ir;     __io  uint32_t dh_ier;   }; } uart_typedef; 

q2. in case of using "union" in "struct" in "struct". benefit , purpose use this?

typedef struct {   union {   struct{     __io   uint32_t ctrlr0;      __io   uint32_t ssi_comp_version;       union {     __io   uint32_t dr;                   __io   uint32_t dr0;                 };     __io   uint32_t dr1;                 __io   uint32_t rsvd_2;          };   uint8_t reserved[0x1000];        }; } ssi_typedef; 

the first case "aliasing" of field names. uart_typedef type consists of 2 uint32_t fields, first can referred of rr, tr, dl or rr_tr_dl. ditto second field, can dh, ir or dh_ier.

the second case, ssi_typedef, similar in respect inner unions, consisting of 3 uint32_t fields, ctrlr0/ssi_comp_version, dr/dr0 , dr1/rsvd_2 (in cases, either name can used fields).

but structure whole sized @ 4k, due unioning uint8_t reserved[0x1000].


the aliasing useful if, example, same underlying field can accessed either rr or tr, depending on context. example, device may have different behaviour depending on whether read or write location.

say, example, write given address (a memory mapped i/o operation) indicate other end read-ready (able receive data). further assume reading exact same location let know whether you're able transmit.

first, let's set said memory mapped i/o address (say it's @ 0xf000):

uart_typedef *utd = (uart_typedef *)0xf000; // shifty :-) 

now both these statement refer same memory address:

int transmitready = utd->tr; // can transmit? utd->rr = 1;                 // tell other end can send. 

being able use distinct names same underlying thing can aid readability.





wiki

Comments

Popular posts from this blog

Asterisk AGI Python Script to Dialplan does not work -

python - Read npy file directly from S3 StreamingBody -

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -