Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantages of using union when same thing can be done using struct - C

I have difficulty in understanding the use of union in C. I have read lot of posts here on SO about the subject. But none of them explains about why union is preferred when same thing can be achieved using a struct.

Quoting from K&R

As an example such as might be found in a compiler symbol table manager, suppose that a constant may be an int, a float, or a character pointer. The value of a particular constant must be stored in a variable of the proper type, yet it is most convenient for table management if the value occupies the same amount of storage and is stored in the same place regardless of its type. This is the purpose of a union a single variable that can legitimately hold any of one of several types. The syntax is based on structures:

union u_tag {
      int ival;
      float fval;
      char *sval;
} u;

The usage will be

if (utype == INT)
    printf("%d\n", u.ival);
if (utype == FLOAT)
    printf("%f\n", u.fval);
if (utype == STRING)
    printf("%s\n", u.sval);
else
    printf("bad type %d in utype\n", utype);

The same thing can be implemented using a struct. Something like,

struct u_tag {
    utype_t utype;
    int ival;
    float fval;
    char *sval;
} u;

if (u.utype == INT)
    printf("%d\n", u.ival);
if (u.utype == FLOAT)
    printf("%f\n", u.fval);
if (u.utype == STRING)
    printf("%s\n", u.sval);
else
    printf("bad type %d in utype\n", utype);

Isn't this the same? What advantage union gives?

Any thoughts?

like image 876
Navaneeth K N Avatar asked Jul 28 '10 11:07

Navaneeth K N


2 Answers

In the example you posted, the size of union would be the size of float (assuming it is the largest one - as pointed out in the comments, it can vary in a 64 bit compiler), while the size of struct would be the sum of sizes of float, int, char* and the utype_t (and padding, if any).

The results on my compiler:

union u_tag {
    int ival;
    float fval;
    char *sval;
};
struct s_tag {
    int ival;
    float fval;
    char *sval;
};

int main()
{
    printf("%d\n", sizeof(union u_tag));  //prints 4
    printf("%d\n", sizeof(struct s_tag)); //prints 12
    return 0;
}
like image 160
Amarghosh Avatar answered Nov 15 '22 06:11

Amarghosh


Unions can be used when no more than one member need be accessed at a time. That way, you can save some memory instead of using a struct.

There's a neat "cheat" which may be possible with unions: writing one field and reading from another, to inspect bit patterns or interpret them differently.

like image 38
Michael Foukarakis Avatar answered Nov 15 '22 07:11

Michael Foukarakis