Union is a user-defined data type in C, which stores a collection of different kinds of data, just like a structure. However, with unions, you can only store information in one field at once. This tutorial guides you on how to use Union in C Programming



  • Union is like struct, except it uses less memory.
  • The keyword union is used to declare the union 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


Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram