C Unions

Union is define like structure but instead of “struct” keyword we use “union” keyword. It is a special feature of C programming which allow you to store different data types in the same memory location.

Syntax of a union:

union employee

{

            union-member1;

            union-member2;

            ………….

            union-memberN;

};

We can define a union with many members, but only one member can access at a time. Means we can store value of only one variable at any given time.

Here defining a variable of type union:

union employee

{

            char name[50];

            int age;

            float salary;

};

Declaration of union:

union employee

{

            char name[50];

            int age;

            float salary;

}emp1, emp2, emp[10];

Or we can declare like given below

union employee emp1, emp2, emp[10];

The memory allocated for the union variable is always equal to its largest member so a union variable can hold value of its one member variable at any given time. Example memory occupied by union variable emp1 is equal to memory taken by memeber1 variable i.e. 50 bytes.

Accessing union members

  1. union member access by using member access operator( . )

See an example given below

#include <stdio.h>#include <string.h>

union employee

{

            char name[50];

            int age;

            float salary;

};

int main()

{

    union employee record1;

    union employee record2;

     /* Assigning values to record1 union variable */

      strcpy(record1.name, “Gyan”);

       record1.age = 30;

       record1.salary = 30000;

        printf(“Printing Values of Union record1\n”);

       printf(“Record1 Name = %s\n”,record1.name);

       printf(“Record1 age = %d \n”,record1.age);

       printf(“Record1 salary = %d\n”,record1.salary);

     /* Assigning values to record2 union variable */

       printf(“Printing Values of Union record2\n”);

      strcpy(record2.name, “Ramesh”);

       printf(“Record2 Name = %s\n”,record2.name);

       record2.age = 32;

       printf(“Record2 age = %d \n”,record2.age);

      record2.salary = 35000;

       printf(“Record2 salary = %d\n”,record2.salary);

        return 0;

}

Output:

Printing Values of Union record1

Record1 Name =

Record1 age =

Record1 salary = 30000

Printing Values of Union record2

Record2 Name = Ramesh

Record2 age = 32

Record2 salary = 32000

Explanation: In first union variable record1 we are assigning name, age and salary before printing, but it is  printing only value of salary, because a union variable can holds value of its one member at a time and last updated member is “salary”. In another union variable record2 values of all members are printing on console, because we are assigning and accessing one by one.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.