Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is a Structure in C?
2.1.
Example of structure in C
2.2.
C
3.
What is a Union in C?
3.1.
Example of Union in C 
3.2.
C
4.
Functions and Similarities Between Union and Structure in C
5.
Difference Between Structure And Union In C
6.
Advantages of Structure in C
7.
Advantages of Union in C
8.
Drawbacks Of Structure Vs Union In C
9.
Frequently Asked Questions
9.1.
What is structure and union in C?
9.2.
Which is better, union or structure?
9.3.
Why is union used in C?
9.4.
What are the two types of unions?
9.5.
What is the relationship between structures and arrays?
10.
Conclusion
Last Updated: Mar 27, 2024
Easy

Difference between structure and union in C

Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

In C programming, structures and unions are essential user-defined data types. The structure in C programming combines variables of different types, while union in C programming is more suitable for handling unknown data types. Structure in C programming is often preferred for its versatility, despite challenges such as memory allocation for individual members.

Introduction

Structure in C utilizes the total memory occupied by all components, while union occupies memory based on its largest member. Despite this, the structure is more versatile, offering procedural functionalities like initializing or loading multiple components simultaneously.
Let’s check what the difference between structures and unions are, their advantages, drawbacks, and differences.

Also See, Sum of Digits in C, Short int in C Programming and C Static Function

What is a Structure in C?

Structures are data types that combine data items that have a logical relationship. Structures are capable of containing multiple members that are of different data types under a single name. Structures can also locate and access individual components in parallel at the same time.

Thus, being able to initialise multiple members concurrently. This is due to all the elements in the structure being stored at contiguous memory allocations. 

Struct is used to define structures. Here is an example of how “struct” is used to incorporate different members.

struct example{ example_member; example_member2; };

Let us check how to define a structure we will name, “student”.

struct student{
char student_firstname[50];
char student_lastname[50];
int student_age;}

When accessing structure members, we must use dot operators between the names and the members of the structure. For instance, in the student structure, we must use: “student.student_firstname”. 

Example of structure in C

Here is an example of using structures in C:

  • C

C

#include <stdio.h>
struct pokemon {
char pokemon_name[70];
int pokedex_no;
float hp;
} sdt;
int main() {
printf("Pokemon information:\n");
printf("Enter pokemon name: ");
fgets(sdt.pokemon_name, sizeof(sdt.pokemon_name), stdin);
printf("Enter pokemon id: ");
scanf("%d", & sdt. pokedex_no);
printf("hp: ");
scanf("%f", & sdt.hp);
printf("Thanks for the information: \n");
printf("Pokemon name: ");
printf("%s", sdt.pokemon_name);
printf("Pokemon pokedex number: %d\n", sdt. pokedex_no);
printf("Pokemon HP: %.1f\n", sdt.hp);
return 0;
}

This is how the output would look like:

Output1
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

What is a Union in C?

A union in C is a user-defined data type that allows storing different data types in the same memory location. Unlike structures, where each member has its own memory space, a union shares memory among its members, allowing only one member to be active at any given time. This makes unions efficient for conserving memory when different types of data need to be stored interchangeably.

Let us check how to define a union known as “student”.

union student{
char student_firstname;
char student_lastname;
int student_age;
double student_height;}

We can then use “Student newStudent” to declare the function and dot operators are also used when trying to reach different data types.

Example of Union in C 

Student newStudent; 
 newStudent.age = 15; 
 newStudent.height = 5.11;

Here is an example of using unions in C where the output gets corrupted due to the memory location being shared by all the member data types:

  • C

C

#include <stdio.h>

union stats
{
int revenue;
float total_sales;
char condition;
};

int main( )
{
union stats it;
it.revenue = 5000;
it.total_sales = 7000;
it.condition = 'p';

printf("%d\n", it.revenue);
printf("%f\n", it.total_sales);
printf("%c\n", it.condition);

return 0;
}

Output:

Output2

You can also read about the dynamic arrays in c, and  Tribonacci Series

Functions and Similarities Between Union and Structure in C

Feature Union Structure
Definition User-defined data type allowing storage of different data types in the same memory location. User-defined data type that combines variables of different data types under a single name.
Memory Allocation Shares memory among its members, occupying memory based on the largest member. Allocates memory for each member separately, utilizing the total memory occupied by all members.
Access to Members Only one member can be active at a time. All members can be accessed simultaneously.
Size Size is determined by the largest member. Size is the sum of the sizes of all members.
Usage Efficient for conserving memory when different types of data need to be stored interchangeably. Preferred for organizing data of different types into a single entity.
Versatility Less versatile compared to structures. More versatile, offering procedural functionalities like initializing or loading multiple components simultaneously.

Difference Between Structure And Union In C

Structure Union
Allocates memory for each member separately. Shares memory among its members, based on largest member.
Size is the sum of the sizes of all members. Size is determined by the largest member.
All members can be accessed simultaneously. Only one member can be active at a time.
Used to organize data of different types into a single entity. Efficient for conserving memory when storing interchangeable data types.
More versatile, offering procedural functionalities. Less versatile compared to structures.

Advantages of Structure in C

  • A structure can contain multiple data items with similar attributes inside the same memory location. This is especially helpful when gathering data about the same subjects with similar parameters.
  • Structures are stable and easier to maintain as the entire records can be represented under a single name. This allows us to pass functions with complete sets of records using single parameters.
  • Arrays of structures can be used to effectively incorporate more records with similar data types.

Advantages of Union in C

  • Unions are popular for occupying less memory.
  • Unions are helpful when storing the data of a single data member. And, unions are especially useful for storing multiple data members in the same memory location.

Drawbacks Of Structure Vs Union In C

Structures and unions both have their own set of drawbacks. Using unions sometimes can cause massive errors in functions due to the nature of combining every single member when passing a function.

Meanwhile, structures pose a problem for scalability and they become harder to manage when projects become complex, requiring much more storage as well.

Let us learn the different disadvantages that we face when working with each one of them.

Structures

  • Changes in any data structure require changes at multiple other places in the code. This makes it more time-consuming to use and harder to track.
  • Structures are slower and require dedicated memory for all their data.

Unions

  • Members cannot be processed with varying values simultaneously. Users are limited to using a single member.
  • Unions assign a single memory location for their members, thus causing complexities, cluttering and many other errors when working with varying data types. All of this is due to not having dedicated memory allocations.

Frequently Asked Questions

What is structure and union in C?

Unions and structures are user-defined data types that can be used for combining multiple data items with various attributes and passing functions through incorporating these data items.

Which is better, union or structure?

Structures are more suitable for reliable and consistent performance when working with multiple data types. However, unions are less memory-intensive and are more effective when working with a massive number of members or objects.
Structures are convenient but not made for large projects. Structure and union differences in c can be easily noticed when working with different data types possessing various attributes or when there are a huge number of data items.

Why is union used in C?

Unions are used in C to define functions for multiple data items, which are of different data types. Unions are highly used especially when data types are unknown.

What are the two types of unions?

The two types of unions are tagged and untagged unions. Tagged unions are capable of handling variable but fixed data types. Meanwhile, untagged unions are used when not wanting to allocate space for storing the data type tag.

What is the relationship between structures and arrays?

Like there are arrays of other data types, there can be arrays of structures as well. Similarly, structures can contain arrays as well. Structures and arrays can also be used together to create a nested representation when dealing with arbitrary levels of complexity.

Conclusion

Both structures and unions offer their own set of benefits and disadvantages. It really comes down to a matter of preference and the scale of the program (or project) when deciding if one should use structures or unions. While structures are more adaptive, versatile, and capable of accessing multiple objects parallelly, unions are much more portable and easy to debug.

Deciding which data type to use in C depends on the type of data items that will be used and how they are related to each other. Unions are the best when using data types that are unknown, while structures are best for working with objects (data) with different attributes.

You can also consider our Online Coding Courses such as the DSA in PythonC++ DSA CourseDSA in Java Course to give your career an edge over others.

 

Previous article
Introduction to union
Next article
Memory layout of C program
Live masterclass