Union in C

A Union is a collection of different data types that are stored under a common name. 

It is similar to the structure but it holds only one member at a time. All members will share the same memory location in a union in C. 

A union variable requires the memory that is equal to the number of bytes for the largest member in the union.

The syntax is

union unionname
{
 datatype element1;
 datatype element2;
….
Datatype element n;
};
Union unionname var1, var2,var3,….var n;

Ex: 

Union books
{
  Int pages;
  float price;
  char author[50];
} u;

Note: The union variable u occupies 30 bytes of memory. The elements of the memory can be accessed by (.) operator.

C program to declare a book as a union and display its details

#include <stdio.h>
#include <string.h>
// Define a union to represent different types of books
union Book {
    struct {  // Structure for fiction books
        char title[50];
        char author[50];
        char genre[20];
    } fiction;
    struct {  // Structure for non-fiction books
        char title[50];
        char author[50];
        char subject[30];
    } nonfiction;
};
int main() {
    union Book book;  // Declare a book variable of type union Book
    int choice;
    printf("Enter book type (1 for fiction, 2 for non-fiction): ");
    scanf("%d", &choice);
    // Get book details based on user choice
    if (choice == 1) {
        printf("Enter fiction book title: ");
        scanf("%s", book.fiction.title);
        printf("Enter fiction book author: ");
        scanf("%s", book.fiction.author);
        printf("Enter fiction book genre: ");
        scanf("%s", book.fiction.genre);
    } else if (choice == 2) {
        printf("Enter non-fiction book title: ");
        scanf("%s", book.nonfiction.title);
        printf("Enter non-fiction book author: ");
        scanf("%s", book.nonfiction.author);
        printf("Enter non-fiction book subject: ");
        scanf("%s", book.nonfiction.subject);
    } else {
        printf("Invalid choice!\n");
        return 1; // Exit with an error code
    }
    // Display book details based on user choice
    printf("\nBook Details:\n");
    if (choice == 1) {
        printf("Title: %s\n", book.fiction.title);
        printf("Author: %s\n", book.fiction.author);
        printf("Genre: %s\n", book.fiction.genre);
    } else {
        printf("Title: %s\n", book.nonfiction.title);
        printf("Author: %s\n", book.nonfiction.author);
        printf("Subject: %s\n", book.nonfiction.subject);
    }
    return 0; // Exit successfully
}

Output:

Enter book type (1 for fiction, 2 for non-fiction): 1
Enter fiction book title: Graduate
Enter fiction book author: Lokesh
Enter fiction book genre: students
Book Details:
Title: Graduate
Author: Lokesh
Genre: students

difference between structure and union in C

Structure Union 
Every member of the structure has its own memory space to store the values.All the members of the union use the same memory space to store the values.
The keyword struct is used to define the structure.The keyword union is used to define a union.
All the members of the structure can be accessed in a single instance.Union access only one member at a time because all the members use the same memory space.
More storage space is required.Less storage space is required.
Different interpretations for the same memory location is not possible in structures.Different interpretations for the same memory location are possible in unions.
It may be initialized with all its members.Only the first member of the union may be initialized.

FAQs of a union in C

  1. What is a union in C, and how does it differ from a structure?

    A union is a user-defined data type that allows storing different types of data in the same memory location. 
    Unlike a structure, where each member has their own memory, union members share the same memory. 
    This means only one member of the union can hold a value at any given time.

  2. Why would you use a union instead of a structure?

    Unions are used primarily to save memory when you know only one data type will be used at a time. 
    They’re also helpful when you need to interpret the same memory area in different ways (e.g., treating a byte as an integer or a character).

  3. How do I access and modify the members of a union in C?

    You use the dot (.) operator, just like with structures. For example, if you have a union named data with members int num and char letter, you would access them as data.num and data.letter, respectively. Remember to modify only the active member to avoid unexpected results.

  4. What is the size of a union in C?

    The size of its largest member determines the size of a union. 
    This is because enough memory must be allocated to accommodate any of the possible data types stored within the union.

  5. Are there any potential drawbacks or pitfalls to using unions in C?

    Yes, the main risk is accidentally accessing the wrong member. 
    Since only one member is active at a time, reading from or writing to an inactive member can lead to unexpected and incorrect results. 
    Additionally, unions require careful management to ensure type safety.

Scroll to Top