Fill your College Details

Summarise With AI
Back

Difference Between Structure And Union In C

13 Jun 2026
5 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 ===

🎯 Calculate your GPA instantly — No formulas needed!!

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 the difference between structure and union in C:

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 ===

How Memory Allocation Works in Structure and Union

The primary difference between a structure and a union lies in how memory is allocated to their members. Understanding this concept helps programmers decide which data type is suitable for a particular use case.

In a structure, each member gets its own separate memory location. As a result, all members can store values simultaneously without affecting one another.

In contrast, a union allocates a single shared memory location for all its members. Since the memory is shared, only one member can hold a valid value at a time. Assigning a value to one member overwrites the previously stored value.

Memory Allocation in Structure vs Union

Feature Structure Union
Memory Allocation Allocates separate memory space for each member. Allocates a single shared memory space for all members.
Total Size Approximately equal to the sum of the sizes of all members (including padding). Equal to the size of the largest member.
Data Storage All members can hold and retain their values simultaneously. Only one member can store a valid value at a time.
Data Overwriting Updating one member does not affect the values of other members. Assigning a value to one member overwrites the previously stored value in the shared memory.
Memory Efficiency Consumes more memory because each member has its own storage space. Consumes less memory because all members share the same memory location.
Best Suited For Applications where multiple data members are used simultaneously, such as employee records and student databases. Applications where memory optimization is important, such as embedded systems, device drivers, and sensor data processing.

Memory Allocation Example

Consider the following declaration:

struct Student {
   int id;
   float marks;
   char grade;
};

union StudentData {
   int id;
   float marks;
   char grade;
};

Assuming:

  • int = 4 bytes
  • float = 4 bytes
  • char = 1 byte

Structure Memory Allocation

The structure allocates separate memory for each member:

Member Size
int id 4 bytes
float marks 4 bytes
char grade 1 byte
Total Size 9 bytes (excluding padding)

Since every member has its own memory space, all values can be accessed independently.

Union Memory Allocation

The union allocates memory based on the size of its largest member:

Member Size
int id 4 bytes
float marks 4 bytes
char grade 1 byte
Total Size 4 bytes

Because all members share the same memory location, storing a value in one member replaces the value stored in another member.

Why Does a Union Occupy Less Memory?

A union occupies less memory because all its members share the same storage space. The compiler allocates memory equal to the size of the largest member rather than the combined size of all members. This makes unions useful in scenarios where memory optimization is important, such as:

  • Embedded systems
  • Device drivers
  • Sensor data processing
  • Hardware programming
  • Communication protocols

Bottom Line

Structures allocate separate memory for each member, allowing multiple values to exist simultaneously. Unions allocate a single shared memory location, making them more memory-efficient but limiting storage to one active member at a time. Understanding memory allocation is essential for choosing between structures and unions in C.

Similarities Between Structure and Union in C

Although structures and unions differ in the way memory is allocated and managed, they share several characteristics because both are user-defined data types in C. Understanding these similarities helps you learn how structures and unions are used to organize and manage related data efficiently.

Similarities Between Structure and Union

Feature Structure Union
User-defined data type Yes Yes
Can store different data types Yes Yes
Members are accessed using the dot (.) operator Yes Yes
Can contain arrays and pointers Yes Yes
Can be nested inside another structure or union Yes Yes
Variables are declared similarly Yes Yes
Can be passed to functions Yes Yes
Support typedef keyword Yes Yes
Used to group related data Yes Yes

Key Similarities Between Structure and Union in C

  • Both are user-defined data types that allow programmers to group related variables under a single name.
  • Both can contain members of different data types, such as int, float, char, arrays, pointers, and even other structures or unions.
  • Members in both structures and unions are accessed using the dot (.) operator and the arrow (->) operator when working with pointers.
  • Both support nested declarations, meaning a structure or union can contain another structure or union as one of its members.
  • Variables of both structures and unions are declared in a similar way, making their syntax easy to understand and use.
  • Both can be passed to functions and returned from functions, enabling modular and reusable code.
  • Both support the typedef keyword, which helps create aliases and improves code readability.
  • Both are widely used to organize related data, making programs easier to manage and maintain.

Example Showing Similarities

struct Student {
   int id;
   char name[20];
   float marks;
};

union Employee {
   int empId;
   char department[20];
   float salary;
};

In the above example, both struct Student and union Employee:

  • Group multiple data members together.
  • Contain different data types.
  • Follow a similar declaration syntax.
  • Allow member access using the dot operator.

Bottom Line

Structures and unions have several similarities in terms of syntax, member access, and functionality. The primary difference lies in memory allocation; a structure allocates separate memory for each member, whereas a union shares the same memory among all its members. Understanding these common features makes it easier to decide when to use a structure and when to use a union in C.

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. 

Applications of 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 a 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).

When to Use Structure and Union in C

Structures and unions are designed for different purposes. Although both allow you to group multiple data members under a single name, the choice between them depends primarily on how the data will be used and whether memory optimization is important.

Understanding when to use a structure and when to use a union can help you write programs that are both efficient and easier to maintain.

When Should You Use a Structure?

A structure should be used when all members need to store and retain their values independently. Since each member has its own memory location, modifying one member does not affect the values stored in other members.

Structures are best suited for representing real-world entities that consist of multiple attributes.

Use a Structure When:

  • Multiple members need to be accessed simultaneously.
  • Each member should preserve its value independently.
  • Memory usage is not a major constraint.
  • You are working with record-based data.
  • Data integrity is more important than memory optimization.

Common Scenarios Where Structures Are Used

Student and Employee Records

Applications such as college management systems and payroll systems require storing several attributes together, such as IDs, names, departments, and salaries. Since all values need to be available at the same time, structures are the preferred choice.

Banking and Financial Applications

Bank account information, transaction details, customer data, and balances are typically represented using structures because multiple pieces of information must be maintained simultaneously.

Inventory and Product Management Systems

E-commerce and inventory applications use structures to store details such as product ID, name, quantity, and price, allowing all information to be accessed independently.

Database Management

Structures are widely used to represent records in database systems because each field needs separate storage and should remain unaffected when other fields are updated.

When Should You Use a Union?

A union should be used when only one member needs to store a value at any given time. Since all members share the same memory location, unions provide better memory efficiency but do not allow multiple members to hold valid values simultaneously.

Unions are particularly useful in applications where memory resources are limited or when the same data needs to be interpreted in different ways.

Use a Union When:

  • Only one member will be active at a time.
  • Memory optimization is important.
  • The same memory needs to represent different data types.
  • You are working with low-level or hardware-related programming.
  • Reducing memory consumption is a priority.

Common Scenarios Where Unions Are Used

Embedded Systems

Microcontrollers and IoT devices often have limited memory. Unions help reduce memory usage by allowing multiple variables to share the same storage space.

Device Drivers

Operating systems and hardware drivers frequently use unions to interpret the same memory area in different formats while minimizing memory overhead.

Communication Protocols

Network packets and protocol headers may contain fields that represent different types of information depending on the context. Unions provide a memory-efficient way to handle such data.

Sensor Data Processing

Industrial automation and IoT applications use unions to process sensor readings and convert raw binary data into meaningful values without allocating additional memory.

Real-Time Systems

Applications that require high performance and efficient resource utilization often rely on unions to minimize memory consumption and improve execution efficiency.

Bottom Line

Use a structure when you need to store and maintain multiple pieces of information simultaneously. Use a union when only one member needs to be active at a time and efficient memory utilization is a priority. The choice between the two ultimately depends on the requirements of the application and how the data will be accessed and managed.

Conclusion

Understanding the difference between structure and union in C is essential for choosing the right data type for your program. While structures allocate separate memory for each member and allow multiple values to be stored simultaneously, unions share the same memory space, making them more memory-efficient. Structures are commonly used in applications such as student records and databases, whereas unions are useful in memory-constrained environments like embedded systems and device drivers. By understanding their memory allocation, use cases, and limitations, you can write more efficient and optimized C programs.

Frequently Asked Questions

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

The main difference between structure and union in C lies in memory allocation. A structure assigns separate memory to each member, whereas a union allows all members to share the same memory space, making it more memory-efficient.

2. Can a structure hold different types of data?

Yes, a structure in C can store members of different data types, such as int, float, char, arrays, and pointers. Since each member has its own memory location, all values can be stored and accessed independently without affecting one another.

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

No, all members of a union share the same memory location, so only one member can hold a valid value at a time. When a new value is assigned to a member, it overwrites the value previously stored in the shared memory space.

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

A union is more memory-efficient than a structure because all its members share the same memory location. As a result, the size of a union is determined by its largest member, whereas a structure allocates separate memory for each member, increasing the total memory usage.

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

You should use a structure when multiple data members need to store and retain their values simultaneously. Structures are commonly used for representing records such as student information, employee details, and database entries. In contrast, unions are better suited for applications where only one member needs to be active at a time and memory optimization is important.

Summarise With Ai
ChatGPT
Perplexity
Claude
Gemini
Gork
ChatGPT
Perplexity
Claude
Gemini
Gork
Chat with us
Chat with us
Talk to career expert