C Unions

Unions are user-defined data type in C, which is used to store a collection of different kinds of data, just like a structure. However, with unions, you can only store information in one field at any one time.

  • Unions are like structures except it used less memory.
  • The keyword union is used to declare the structure in C.
  • Variables inside the union are called members of the union.

Defining a Union in C

Syntax:
union unionName
{
   //member definitions
};
Example:
union Courses
{
   char  WebSite[50];
   char  Subject[50];
   int   Price;
};

Accessing Union Members in C

Example:
#include<stdio.h>
#include<string.h>
 
union Courses
{
   char  WebSite[50];
   char  Subject[50];
   int   Price;
};
 
void main( )
{
   union Courses C;
   
   strcpy( C.WebSite, "w3schools.in");   
   printf( "WebSite : %s\n", C.WebSite);
      
   strcpy( C.Subject, "The C Programming Language");    
   printf( "Book Author : %s\n", C.Subject);
   
   C.Price = 0;
   printf( "Book Price : %d\n", C.Price);
}
Program Output:
WebSite : w3schools.in

Book Author: The C Programming Language

Book Price : 0


Scroll Back to Top