data structures - Advantages of using union when same thing can be done using struct - C -
I have difficulty understanding the use of union
in C. I read many posts here But then, none of these tells about why the
Q & R
, as if a compiler symbol can be found in the table manager, suppose that a continuous int, float or a Character Indicators The value of a particular constraint should be stored in the appropriate type of variable, yet it is most convenient for table management if the value is in the amount of storage and regardless of its type in the same place. is stored. The purpose of this union is a single variable which can legally hold one of several types. The syntax is based on the structures:
union u_tag {int ival; Float Peal; Four * average; } U;
will be used
if (UTP == INT) printf ("% d \ n", u.ival); If (UTP == float) printf ("% F \ n", U. Fawley); If (UTP == STRING) printf ("% s \ n", u.sval); Else printf ("bad type% d utype \ n", utype);
The same thing can be implemented using a strat. Something like this,
struct u_tag {utype_t utype; Lifetime; Float Peal; Four * average; } U; If (UUUUE) printf ("% d \ n", u.ival); If (UUUUU = Flat) printf ("% F \ n", U.Faval); If (u.utype == STRING) printf ("% s \ n", u.sval); Else printf ("bad type% d utype \ n", utype);
Is not it?
In the example you posted, the union Size will be the size of the float (it is believed that this is the largest - as mentioned in the observations, it can vary in a 64 bit compiler), while the structure will be float, int, char * and utype_t ( And padding, if any).
Result on my compiler:
union u_tag {int ival; Float Peal; Four * average; }; Struct s_tag {int ival; Float Peal; Four * average; }; Int main () {printf ("% d \ n", size (union u_tag)); // 4 printprint print ("% d \ n", size (struct s_tag)); // print 12 return 0; }
Comments
Post a Comment