c
  1. c-union

C Union

Syntax

The syntax of declaring a union is:

union [union tag] {
   member definition;
   member definition;
   ...
} [one or more union variables];

Example

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

union employee {
        int id;
        char name[20];
        float salary;
};

int main() {
    union employee emp;
    emp.id = 1001;

    printf("Employee ID : %d\n", emp.id);

    strcpy(emp.name, "John");
    printf("Employee Name : %s\n", emp.name);
    
    emp.salary = 5000.00;
    printf("Employee Salary : %.2f", emp.salary);

    return 0;
}

Output

Employee ID : 1001
Employee Name : John
Employee Salary : 5000.00

Explanation

A union in C is a user-defined data type that allows an element to have different data types. It is similar to a structure, but all the members share the same memory location. The memory size of a union is determined by its largest member.

In the above example, we have declared a union called employee which has three members - an integer id, a character array name, and a floating-point number salary. We have then created an instance of the employee union called emp.

We have assigned the value 1001 to the id member and printed it using the printf function. We have then assigned the value "John" to the name member using the strcpy function and printed it using the printf function. Finally, we have assigned a floating-point value of 5000.00 to the salary member and printed it using the printf function.

As all the members share the same memory location, when we change the value of one member, the value of all the other members will be lost. For example, when we assigned "John" to the name member, the previous value of 1001, which was stored in the same memory location, was lost.

Use

Unions are useful for situations where a single memory location needs to be used for different data types at different times. They are also used for saving memory when we know that only one member will be accessed at any given time.

Important Points

  • The members of a union share the same memory location.
  • The memory size of a union is determined by its largest member.
  • Only one member can be accessed at any given time.
  • If a value is assigned to one member, the value of all the other members will be lost.

Summary

A union in C is a user-defined data type that allows an element to have different data types. It is similar to a structure, but all the members share the same memory location. Unions are useful for situations where a single memory location needs to be used for different data types at different times. Understanding the syntax and usage of unions is important for optimizing memory usage in C programs.

Published on: