Back

Difference Between Structure And Union In C

22 Feb 2025
4 min read

In C programming, both structures and unions serve the purpose of combining different data types, but they manage memory usage in distinct ways. A structure allocates separate memory for each of its members, allowing multiple members to hold values simultaneously. Conversely, a union allocates a single memory space for all its members, meaning that only one member can have a value at any given time. As a result, while structures are more versatile, unions offer greater memory efficiency. This highlights the key difference between structure and union in C.

What is a Structure in C?

The "struct" keyword is used to declare a user-defined data type. It creates a single datatype with a single name by combining many datatypes. Contiguous memory regions hold all of a structure's components. The sum of a structure's element sizes determines its overall memory size. The dot (.) operator can be used to access the structure elements. 

Syntax of Structure in C

struct name {
       member1 definition;
       member2 definition;
       ...
       memberN definition;
};

Example 

This C program demonstrates the use of structures. It defines a Person structure with two members: name (a string) and age (an integer). The program creates a Person variable, initialises it with sample data, and prints the details (name and age) to the screen using printf.

Code 

#include <stdio.h>

// Define a structure for a 'Person'
struct Person {
    char name[50];
    int age;
};

int main() {
    // Declare and initialize a 'Person' structure
    struct Person person1 = {"John Doe", 30};
    
    // Print the values of the structure members
    printf("Name: %s\n", person1.name);
    printf("Age: %d\n", person1.age);
    
    return 0;
}

How the code works 

Step 1: The program includes the stdio.h library to use input/output functions like printf.

Step 2: A structure Person is defined with two members: name (a string of characters) and age (an integer).

Step 3: In the main function, a variable person 1 of type struct Person is declared and initialised with the name "John Doe" and age 30.

Step 4: The program prints the values of person1's name and age using printf.

Step 5: The program finishes and exits after printing the details of person 1.

Output

Name: John Doe
Age: 30


=== Code Execution Successful ===

What is a Union in C?

The "union" keyword designates a user-defined data type called a Union. It consists of a group of various data types, and every component is kept in the same memory location. In a union, a value can only be held by one member at a time. The largest union member determines the memory size.

Syntax of Union

union UnionName { 
       dataType member1; 
       dataType member2; 
       // more members 
};

Example

The use of a union in C, which enables the storage of various data types in the same memory address, is demonstrated by this code. An integer, a float, and a character are all present in the union value. The software assigns values to each component one by one, demonstrating how each assignment replaces the one before it. Additionally, it prints the union's size, corresponding to its biggest member's size. 

Code

#include <stdio.h>

union Value {
    int i;
    float f;
    char c;
};

int main() {
    // Create a union variable
    union Value val;

    // Store an integer in the union
    val.i = 10;
    printf("Integer: %d\n", val.i);

    // Store a float in the union (this will overwrite the integer value)
    val.f = 5.75;
    printf("Float: %.2f\n", val.f);

    // Store a character in the union (this will overwrite the float value)
    val.c = 'Z';
    printf("Character: %c\n", val.c);

    // Print the size of the union
    printf("Size of union: %zu bytes\n", sizeof(val));

    return 0;
}

How the code works

  • The union Value contains three members: i (integer), f (float), and c (character).
  • In the main() function, values are assigned to each member individually, and the output is printed.
  • Since all union members share the same memory, the previous value is overwritten each time a new value is assigned.
  • The program also prints the size of the union, which will be the size of the largest member (float in this case).

Output

Integer: 10
Float: 5.75
Character: Z
Size of union: 4 bytes


=== Code Execution Successful ===

Difference Between Structure and Union in C

In C programming, both structures and unions are user-defined data types that allow you to group different types of variables together. However, they differ significantly in how they allocate memory and how their members are accessed. Here’s a comparison of the two:

Aspect Structure Union
Memory Allocation In a structure, each member is allocated its own memory space. The total size of a structure is the sum of the sizes of its members (considering padding for alignment). Each member in the structure can hold different values at the same time. In a union, all members share the same memory location. This means that only one member can hold a value at any given time. The size of its largest member determines the size of the union, as all members use the same memory space.
Accessing Members You can access and store values in all members of a structure independently, as each member has its own allocated space in memory. Since all members of a union share the same memory, storing a value in one member overwrites the values of the other members. You can only access the last assigned value, as other members may be overwritten.
Use Case You use structures when you need to store several connected values of various types that can be accessed and changed separately. For instance, a structure would work best when a person's name, age, and height are displayed. When you need to store multiple data types in the same memory area but only utilize one data type at a time, you use unions. When representing a variable that can store an integer, a floating-point number, or a character—but never more than one at once—this is helpful in scenarios when memory conservation is crucial.
Size The size of a structure is the sum of the sizes of its members, possibly including padding bytes for alignment. The size of a union is the size of its largest member. Since all members share the same memory, the union uses the amount of memory required to store the largest member.
Size of the Data Type The size of a structure is the total memory required to store all its members, including padding. The size of a union is the memory required for the largest member since they all share the same memory space.

Difference Between Structure and Union in C: Code Example

Here’s a quick comparison using simple examples.

Structure

In this example, we’ll see how a structure in C allows you to store different types of data, with each member having its own memory space. It shows that each member can hold its value independently.

Code
#include <stdio.h>
 
// Structure Definition
struct student {
	int id;
	float marks;
	char grade;
};
 
int main() {
	// Declare and initialize structure
	struct student s1;
	s1.id = 101;
	s1.marks = 88.5;
	s1.grade = 'A';
 
	// Display structure values
    printf("Structure: \n");
    printf("Student ID: %d\n", s1.id);
    printf("Marks: %.2f\n", s1.marks);
    printf("Grade: %c\n", s1.grade);
 
	return 0;
}
How the Code Works:

In this example, the student structure contains three members: id (an integer), marks (a floating-point number), and grade (a character). Each of these members has its own memory space, so they store their values independently.

When you assign values to each member (s1.id, s1.marks, and s1.grade), each value remains unchanged by the other. The printf statements print all values independently, showing how they retain their individual values.

Output
Structure:
Student ID: 101
Marks: 88.50
Grade: A
=== Code Execution Successful ===

Union

In this one, we’ll see how a union shares the same memory location for all its members. Only one member can store a value at a time, and the last assigned value is the one you can access.

Code
#include <stdio.h>
 
// Union Definition
union data {
	int id;
	float marks;
	char grade;
};
 
int main() {
	// Declare and initialize union
	union data d1;
	d1.id = 101;
	d1.marks = 88.5;  // This will overwrite the previous value of id.
	d1.grade = 'A';	// This will overwrite the previous value of marks.
 
	// Display union values
    printf("Union: \n");
    printf("ID: %d\n", d1.id);    	// Prints overwritten value
    printf("Marks: %.2f\n", d1.marks); // Prints the last assigned value
    printf("Grade: %c\n", d1.grade);   // Prints the last assigned value
 
	return 0;
}
How the Code Works

In this example, the data union contains three members: id (an integer), marks (a floating-point number), and grade (a character). All members share the same memory space, so when a new value is assigned to one member, it overwrites the previous value.

The union is initialized by assigning values to each member. The value of id is overwritten by marks, and the value of marks is overwritten by grade. When you print each member, you only see the last assigned value ('A' for grade), as the previous values have been overwritten.

Output
Union: 
ID: 1118896193
Marks: 88.50
Grade: A


=== Code Execution Successful ===

Advantages and Disadvantages of Structure

In C programming, a structure is a user-defined data type that allows you to combine multiple variable types into one cohesive entity. Each element of a structure, which may have a different data type, can be accessed with the dot operator. In situations when you need to store and handle several connected data items, structures are frequently utilised. Like every programming feature, they offer a potent means of organising data, but they also have drawbacks. 

Advantages of Structures in C 

Grouping Related Data:

Multiple data elements of various types can be grouped together under a single name, thanks to structures. This aids in the logical arrangement of data. For instance, a structure can be used to collectively store a student's name, age, and grade in a single unit.

Improved Readability:

By providing meaningful names to data collections, the use of structures improves the readability of code. You can send a single structure variable to functions rather than several unrelated variables, which makes function calls more logical. 

Data Encapsulation:

Data can be encapsulated thanks to structures. This makes it simpler to handle and comprehend since similar info is gathered into a single unit. Encapsulation enhances code organisation and is a basic idea in many programming paradigms.

Memory Efficiency:

When working with linked data types, structures enable the effective use of memory. A structure stores all related data in a single memory block that may be altered as a single entity instead of employing distinct variables for every piece of data.

Extensibility:

Structures are quite flexible and can be readily expanded by adding new members without changing the current code. You can add new properties to the structure without changing a lot of the existing code if the requirements change.

Support for Arrays of Structures:

You can store many instances of a comparable type of data by using arrays created with structures. Working with huge data sets that have similar characteristics, such as a list of employees or students, is helpful. 

Disadvantages of Structures in C 

Memory Wastage (Padding):

Because of alignment constraints, memory padding frequently occurs in C structures. This implies that even though the structure's overall size may appear smaller, padding bytes provided for alignment purposes may cause it to appear larger in memory. Memory consumption may become inefficient as a result.

Fixed Size:

A structure's size is set once it has been defined. This implies that you could have to construct a structure with the maximum sizes if you need to store data of different sizes, resulting in memory waste.

Complexity in Large Structures:

Managing and modifying the data can get complicated when working with large structures, particularly those with several or nested members. It may make the code more complex to maintain and debug. 

Accessing Members:

More intricate syntax is needed for structures in order to access their members (for example, by using the dot operator). This can make the code more prone to errors and more difficult to read, particularly when passing code between methods or working with nested structures.

No Built-in Methods:

C structures lack built-in methods or functions to manipulate the data they store, in contrast to objects in object-oriented programming (OOP). You must write functions independently to process or modify the data inside structures.

No Inheritance or Polymorphism:

C structures lack sophisticated capabilities like inheritance and polymorphism, which are necessary for more intricate data modelling because they are not object-oriented. They are, therefore, less adaptable for use when object-oriented design concepts are necessary.

C structures offer a productive method for managing and organising various linked data. They provide notable benefits regarding data encapsulation, readability, and memory efficiency. They do have several disadvantages, though, like memory padding, the intricacy of huge structures, and the absence of sophisticated capabilities present in object-oriented programming. One must know the benefits and drawbacks of using structures in C programming efficiently. 

Advantages and Disadvantages of Union

A union in C is a user-defined data type that permits storing several types of data in the same memory address. When only one member needs to be used at a time, it is helpful for memory-efficient storage.

Advantages of Unions in C

Memory Efficiency:

Because they keep all of their members in one memory place, unions are memory-efficient. When only one member is required at a time, the union's size is determined by the size of its largest member, which helps conserve memory.

Cost-Effective for Multiple Data Types:

A union enables you to store multiple types of data, but only one at a time, without using additional memory. This is very helpful for applications with little memory, such as embedded devices.

Simplifies Code:

Unions make it easier to manage various kinds of data. Data handling and memory management are made simpler by using a single union variable to hold many data kinds rather than having distinct variables for each type. 

Flexible Data Representation:

When you wish to interpret the same data in several ways, unions might be helpful. For instance, depending on the circumstance, the same data could be handled as a character, float, or integer, providing flexibility in data representation.

Useful in Low-Level Programming:

Unions can be used to map data structures that represent various data types or permit access to the same memory address in various formats in low-level programming, such as in hardware programming or operating system architecture.

Disadvantages of Unions in C

Overwrites Data:

A value stored in one member of a union overwrites the values of all other members since all members share the same memory space. If not handled appropriately, this could result in data loss.

Limited to One Member at a Time:

A union is only able to hold one value at a time. In contrast to structures where each member has its own memory space, unions are inappropriate if you need to store numerous values simultaneously.

Harder to Track Data:

It can be difficult to track the type of data currently stored because you can only access one union member at a time. Debugging and code maintenance may become more challenging as a result.

No Type Safety:

Type safety is not included in unions; hence, no automated verification guarantees that the right type is accessed. If the incorrect member is accessed, this could result in undefinable behaviour.

Complexity in Usage:

Unions can make programs more difficult even when they save memory. To prevent problems like data corruption, developers must make sure that the data is managed properly and know when to access each member. 

When it comes to memory efficiency and adaptability for managing various kinds of data, unions in C provide substantial benefits. They do have drawbacks, though, such as the possibility of data management complexity, restricted concurrent access to members, and overwriting of data. When choosing to include unions in a program, it's critical to comprehend these trade-offs. 

Use Case Scenario: Structure And Union

Structures and unions in C are versatile tools that help organize data efficiently. Knowing when to use each is crucial for writing optimal and maintainable code.

1. Structure Use Cases: Structures are ideal when you need to group different data types that are related but should be stored independently. For example, if you want to represent a student's information, such as their id, name, and marks, a structure is the best choice. This is because each member can hold its own value without affecting the others. Structures are widely used in scenarios like:

  • Data Records: Storing and managing complex data records like employee details, product information, or student databases.
  • Function Arguments: Passing multiple values to functions in an organized way.
  • Linked Lists and Trees: Defining nodes that have multiple fields, like pointers and data values.

2. Union Use Cases: Unions are useful when you need to store different data types in the same memory space, but only one value is needed at any given time. This makes them memory efficient but also limits access to only one member at a time. Unions are commonly used in:

  • Memory Optimization: When memory is limited, and only one value is required at a time, unions help save space. For instance, in embedded systems or system-level programming.
  • Type Conversion: Interpreting the same memory in different ways, like viewing an integer as a float or character array.
  • Variant Data Types: When creating structures where a variable can hold different types of data (e.g., an integer, float, or string, but never more than one at once).

Similarities between Structure and Union in C

Structures and unions in C share several similarities despite their differences in memory management. Understanding these common features helps in using them effectively:

  • Accessing Members: In both structures and unions, members are accessed using the dot (.) operator. For example, student.id or data.value.
  • Pointer Access: If a pointer is used, members are accessed using the arrow (->) operator. For instance, ptr->name is used when accessing members through a pointer.
  • Custom Data Types: Both can be used to define custom data types. After definition, you can declare variables of that type, making code more readable and organized.
  • Nested Definitions: You can nest structures inside unions and vice versa, allowing the creation of complex data models. This is useful in scenarios like embedded systems or data packets.
  • Memory Allocation: Both are stored in contiguous memory locations. This helps in maintaining data locality, which improves cache performance.
  • Function Parameters: Structures and unions can be passed as arguments to functions and returned from functions, allowing modular code design.
  • Array Declaration: Arrays of structures or unions can be declared, enabling the storage of multiple data records efficiently.
  • Initialization: Both can be initialized at the time of declaration, making it easier to set default values or configurations.

Other Datatypes in C Programming Language

C provides a variety of data types to handle different kinds of data efficiently. These are categorized as follows:

1. Primary Data Types: int, float, double, char, and void.

2. Derived Data Types: Arrays, pointers, and functions.

3. User-Defined Data Types: Structures (struct), unions (union), enumerations (enum), and typedef.

4. Complex Data Types: Pointers to functions, pointers to arrays, and structures with pointers.

Conclusion

In summary, unions and structures aggregate different data, but they allocate memory differently. A union allots the same memory space to all of its members, but a structure allots distinct memory to each member. While unions are memory-efficient when only one value needs to be saved at a time, structures are appropriate for holding numerous independent values.

Frequently Asked Questions

1. What is the main difference between a structure and a union in C?

While a union uses the same memory space for all of its members, a structure allots distinct memory for each member.

2. Can a structure hold different types of data?

Yes, several members of various data kinds can be stored independently within a structure.

3. Can we access all members of a union at the same time?

No, a union can only store and access one member at a time because all members share the same memory location.

4. Which is more memory-efficient: structure or union?

A structure utilises memory for each member separately, whereas a union uses only the memory needed for its largest member, making it more memory-efficient.

5. When should I use a structure instead of a union?

Use a structure when you need to store several values at once, each with its own memory space. Use a union when storing multiple kinds of data, but only one at a time. 

Read More Articles

Chat with us
Chat with us
Talk to career expert