Unions in C

Unions are similar to structures. The syntax to declare/define a union is also similar to that of a structure. The only differences is in terms of storage. In structure each member has its own storage location, whereas all members of union uses a single shared memory location which is equal to the size of its largest data member.

loops in c

Syntax

union [union_tag]
{
    //member variable 1
    //member variable 2
    //member variable 3
    ...
}[union_variables];

Example

union Employee
{
     char name[30];
     int age;
     char gender;
}emp1;

Since union uses shared memory, it cannot handle all the members at the same time. Here we have declared name array of size 30 which occupies 30 bytes, age of type int which holds 2 bytes and gender of type char which holds 1 byte.

Now name variable which has the size of 30 is allocated the memory address and the rest of the variables will share that memory space instead of allocating separate memory location.

Accessing the union members is similar to structure. We use the same dot . notation.

union Employee
{
     char name[30];
     int age;
     char gender;
}emp1;

//to access members of union
emp1.name;
emp1.age;
emp1.gender;

Example for union

#include<stdio.h>

union Employee
{
     char name[30];
     int age;
     char gender;
}emp1;
int main( )
{
    union Employee emp;
    strcpy(emp.name,???Andrew???);
    emp.age = 25;
    emp.gender = <span class='highlighter'>M</span>;
    
    printf("%s\n", emp.name);
    printf("%d\n", emp.age);
    printf("%c\n", emp.gender);
    
    return 0;
}

Output

M
77
M

This creates some weird output since the memory address is reused by the 3 variables.


Most Read