TeachingBee

Union in C With Program

Union in C -teachingbee

What is a Union in C?

A union in C is a user defined data type that allows you to store different data types in the same memory location. Unlike structures, where each member has its own memory space, all members of a union share the same memory space. This makes unions efficient for situations where you need to represent different types using the same memory block. A union can include multiple members but only one member will be there that can store a value at any given time.

union in c

Memory Allocation of Union in C

One of the key aspects of unions is their memory allocation. The size of a union is determined by the size of its largest member. This is because all members share the same memory space, and the union needs to be large enough to accommodate the largest data type.

Here’s an example to illustrate how the size of a union is calculated:

#include <stdio.h>

union ExUnion {
    int intnum;
    float floatnum;
    char stringVal[20];
};

int main() {
    union ExUnion ex;
    
    printf("Size of ExampleUnion: %lu bytes\n", sizeof(ex));

    return 0;
}

Output

su

Syntax of Union in C

The syntax of a Union can be divided into three parts:

  1. Union declaration
  2. Union variable
  3. Accessing / Initializing union members

1. Union Declaration

union union_name {
    // Member 1
    data_type1 member1;

    // Member 2
    data_type2 member2;

    // ...

    // Member N
    data_typeN memberN;
};

2. Union Variable

With Union declaration

union union_name {
    // Member 1
    data_type1 member1;

    // Member 2
    data_type2 member2;

    // ...

    // Member N
    data_typeN memberN;
} variable_name;

After Union declaration

union union_name variable_name;

3. Accessing / Initializing Union Members

variable_name.member1 = value1;
variable_name.member2 = value2;
// ...
variable_name.memberN = valueN;

Union Program in C

Write a program in C to store and manipulate information about different shapes. The information to be stored includes either the radius of a circle, the side length of a square, or the base and height of a triangle. Use a union to efficiently represent these different types of shapes in a single data structure.

Algorithm

  1. Define a union named “Shape” with three members: “radius” for a circle, “sideLength” for a square, and a nested struct containing “base” and “height” for a triangle.
  2. Declare a variable of type “Shape” named “myShape”.
  3. Then initialize the “radius” member to represent a circle.
  4. Print information about the circle.
  5. Change the shape type to a square by updating the “sidelength”.
  6. Print information about the square.
  7. Change the shape type to a triangle by updating the “base” and “height”.
  8. Print information about the triangle.

Source Code

#include <stdio.h>

union Shape {
    float radius;
    float sideLength;
    struct {
        float base;
        float height;
    } triangle;
};

int main() {
    union Shape myShape;

    myShape.radius = 5.0;

    printf("Shape Type: Circle\n");
    printf("Radius: %.2f\n", myShape.radius);

    myShape.sideLength = 4.0;
    printf("\nShape Type: Square\n");
    printf("Side Length: %.2f\n", myShape.sideLength);

    myShape.triangle.base = 3.0;
    myShape.triangle.height = 6.0;
    printf("\nShape Type: Triangle\n");
    printf("Base: %.2f\n", myShape.triangle.base);
    printf("Height: %.2f\n", myShape.triangle.height);

    printf("\nSize of Shape: %lu bytes\n", sizeof(myShape));

    return 0;
}

Output

up

Advantages of Union in C

  1. Unions allow multiple members to share the same memory space. This enables efficient memory usage.
  2. Unions offer versatility by enabling a single variable to represent different data types.
  3. Accessing a member of a union involves direct access to shared memory, which can be more memory-efficient compared to maintaining separate variables.

Disadvantages of Union in C

  1. Unions can only hold one member’s value at a time. If there is a need to store and manipulate multiple types of data simultaneously, unions may not be the most suitable choice.
  2. Since all members share the same memory space, accessing a member with an incorrect type can result in undefined behavior.

Conclusion

In the C programming language, a union is a user-defined data type that allows different data types to be stored in the same memory location. It offers a powerful and efficient way to work with different data types in a single memory location. The size of a union is determined by the size of its largest member. By understanding their syntax and applications, you can enhance your ability to write flexible and memory-efficient code. Happy Learning!

I hope You liked the post 👍. For more such posts, 📫 subscribe to our newsletter. Try out our free resume checker service where our Industry Experts will help you by providing resume score based on the key criteria that recruiters and hiring managers are looking for.

FAQ

Can a union have a member that is a structure?

Can unions be used for type casting in C?

When should I use a union in my C program?

How do unions differ from structures in C?

90% of Tech Recruiters Judge This In Seconds! 👩‍💻🔍

Don’t let your resume be the weak link. Discover how to make a strong first impression with our free technical resume review!

Related Articles

Subtraction of Two Numbers Program in C

In this blog post, we will checkout the Subtraction of Two Numbers Program in C. How to Write Subtraction Program in C? To create a C program to subtract two

Add Two Numbers In C

In this blog post, we will checkout the how to add two numbers in C. Algorithm to Add Two Numbers in C To create a C program to add two

Why Aren’t You Getting Interview Calls? 📞❌

It might just be your resume. Let us pinpoint the problem for free and supercharge your job search. 

Newsletter

Don’t miss out! Subscribe now

Log In