C Unions

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

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.