Union in C

By | August 23, 2020

In this article, you’ll learn about unions in C programming. More specifically, how to create unions, access its members and learn the differences between unions and structures.

User defined data type : Union

Like structures in C, union is a user defined data type. In union, all members share the same memory location.

Unions are conceptually similar to structures.. Structs allocate enough space to store all its members wheres unions allocate the space to store only the largest member. The syntax to declare/define a union is also similar to that of a structure.

Syntax of Union :

We use the union keyword to define unions.

struct structureName 
{
    dataType member1;
    dataType member2;
    ...
}; [Structure variables name] // optional 

Declaration of Union

We can declare the C union variables in multiple ways.

First approach :
Declaring the Union first, and then in the main function create the union variable.

union Books {
   char  title[50];
   char  author[50];
   char  subject[100];
   int   book_id;
} ;

// creating union variable

 union Books book1, book2;

    // initialing member of book1 in one statement
struct book1 = {Title of book1, name of author1, 
                        subject of book1, book1 id} ;

Here, book1 and book2 are the variables of data type union.

Second approach :
Create union variables at the time of the C union declaration.

union Books {
   char  title[50];
   char  author[50];
   char  subject[100];
   int   book_id;
} book1, book2 ;


// initialing member of book1 in one statement
struct book1 = {Title of book1, name of author1, 
                        subject of book1, book1 id} ;

Access members of union

We use the dot/member (.) operator to access members of a union. To access pointer variables, we use also use the ( -> ) operator.

Important points

  • Union allocates one common storage space for all its members.
  • Size of a union is taken according the size of largest member in union.
  • Union occupies lower memory space over structure.
  • We can access only one member of union at a time.
  • Unions can be useful in many situations where we want to use the same memory for two or more members.



Please write comments if you find anything incorrect. A gentle request to share this topic on your social media profile.