What is Union in C Language?

This C Tutorial explains Union and its initialization in C Language with examples.

A union is altogether different from structure but declared like structure. For example,

union {
        int x;
        float y;
        char c;
    } val;

Notice that in above declaration, union is declared just like structure but amount of memory allocated to union is as large as the largest member of the union. Since, ‘int’ and ‘float’ both take 4 bytes of storage on Linux and ‘char’ takes just 1 byte. Therefore, ‘val’ is allocated 4 bytes of storage. This means that union ‘val’ is allocated enough memory to accommodate the largest member of it.

What about the other member’s of ‘val’? Where else will they be stored? Actually, unions are useful where all member’s of it refer to same memory location but different member’s occupy the same memory at different times. For example,

/* udec.c -- program declares a union and computes it's size */
#include <stdio.h>
 
/* union declaration */
typedef union {
               float marks;
               char str[20];
               int count;
        } Record;
 
int main(void)
{
    Record new;
 
    puts("**Program computes size allocated to \'new\'**");
    printf("%d bytes allocated to \'new\' Record.\n", sizeof(new));
    return 0;
}

Output follows,

advertisement
advertisement
**Program computes size allocated to 'new'**
20 bytes allocated to 'new' Record.

Notice that ‘new’ Record is allocated 20 bytes which is size of ‘str’, a charater array, the largest member of ‘new’ Record. Now, this memory can be used by all of the members of ‘new’ but not at the same time. Let’s initialize ‘new’,

    Record new = {23.34, "hello", 200};

What do you notice? There’s a warning, when you compile this line, and this is as,

warning: excess elements in union initializer [enabled by default]

This warning is due to the fact that only one member, only first, can initialize the ‘new’ Record. If you initialize ‘new’ Record with value of second or third member, then value gets type cast to type of first member and will be interpreted accordingly.
Okay! We run the program and observe the output below,

advertisement
**Program computes size allocated to 'new'**
20 bytes allocated to 'new' Record.
Let's access 'new' member's...
new.marks is 23.34
new.str is R��A
new.count is 1102755922

Notice that only first member, ‘marks’, gets the right value. What happened with other two member’s values? Actually, when we had initialized ‘new’, 20 bytes occupied by value of first member ‘marks’ and not by any of other members. When we wished to obtain the value of ‘marks’, bits in that memory location interpreted as float and right value got printed. And when next statement executed, bits in the same location interpreted as a string and finally bits in the same location interpreted as an integer value. Therefore, wrong result for other last two members.

advertisement

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

If you wish to look at all C Tutorials, go to C Tutorials.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.