Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C union assignment

Tags:

c

unions

I have union that represent some structures that all uint32 type but with different bit-fields. can i do assignment of one union to other like this:

typedef union foo_u
{
   // raw
   uint32_t foo32;

   // interpretation 1
   struct
   {
      uint16_t a;
      uint16_t b;
   } foo_flavor1;

   //interpretation 2
   struct
   {
      uint32_t a        : 16;
      uint32_t b        : 12;
      uint32_t c        : 4;
   } foo_flavor2;
} foo;
foo a;
foo b;
a.foo32 = 10;
b.foo32 = 30;
b=a;

or i have to do the assignment like this:

b.foo32 = a.foo32; 
like image 250
user2303749 Avatar asked May 18 '26 18:05

user2303749


1 Answers

b = a;

It's totally OK to do this.

For structures and unions, assigning one to another of the same type is well-defined by the standard, and it's guaranteed that after the assignment, they should contain exactly the same data (padding excluded, if present).

like image 112
iBug Avatar answered May 20 '26 07:05

iBug



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!