Structures and Unions manage data in different ways. A Structure allocates specific memory for each input, storing multiple values simultaneously. Whereas a Union shares one memory for all inputs, holding only one value at a time. Structures are handy when you need separate storage, while Unions save space by sharing memory.
In this article we will discuss about Structure and Union user-defined data types and how they differ from each other. We will also discuss its advantages and disadvantages
A structure is defined as a user-defined data type, which allows the user to create a data type that is used to group items of different data types into a single type. In the case of structure, all the members have different memory locations.
In order to create a structure, the ‘struct’ keyword is used. There are two types of members in structures in C++:
Data Members: These are normal C++ variables, a structure can have variables of different data types in C++.
#include<iostream>
using namespace std;
struct rectangle{
int x; // length
int y; // width
int area()
{ return x * y; }
};
int main(){
struct rectangle r;
r.x=5; // length
r.y=3; // width
cout<<"Area of rectangle "<<r.area()<<endl;
}
Output
Area of rectangle 15
What is a Union?
A union is also a user-defined data type that allows the user to group different data types into a single type, but the union reserves the same memory location for all its data members.
In order to declare a union in C++, the keyword ‘union’ is used. Just like structure, it too has data members and member functions
union Union_Name{
Member1,
Member2,
.
.
.
MemberN,
};
Example
#include<iostream>
using namespace std;
union rectangle{
int x,y; // length, width
};
int main(){
union rectangle r;
r.x=5;// assigning only the length
cout<<"The length of rectangle is "<<r.x<<" and the width is "<<r.y<<endl;
r.y=3; //assigning only the width, without changing the length
cout<<"The length of rectangle is "<<r.x<<" and the width is "<<r.y<<endl;
}
Output
The length of rectangle is 5 and the width is 5
The length of rectangle is 3 and the width is 3
Explanation
In the case of union, all the members share the same memory location as a result of which when we assign value to one member of the union, it affects the other members too, because of which when we assign x the value 5, y automatically gets the value 5 and same is the case when we assign y the value 3.
To declare a Structure the keyword 'struct' is used.
1.To declare a Union the keyword 'union’ is used.
2. The compiler allocates the memory for each member when a variable is associated with a structure. The size of a structure is greater or equal to the sum of the sizes of its members.
2. The compiler allocates memory by considering the size of the largest member when a variable is associated with union. The size of the union is equal to the size of the largest Member.
3. Each member within a Structure is assigned a unique storage area of location.
3. All the members of the union share the same memory allocated.
4. The address of each member in the structure is in ascending order, that is, memory for each member starts at different offset values.
4. The address is the same for all the members of a union, that is, every member begins at the same offset value.
5. Manipulation of one member of structure won't affect the values of any other member
5. Manipulation of one member will affect the other members' value in case of union.
6. We can initialize multiple variables at a time.
6. Only the first data member can be initialized.
7. A structure allows accessing and retrieving any data member at a time.
7. A union allows retrieving only one data member at a time.
Example of Structure and Union showing the difference in C
Below is an example of a code that depicts the difference between structure and union Implementation
#include <stdio.h>
#include <string.h>
// Define a structure
struct NinjaStudent {
char name[50];
int age;
float gpa;
};
// Define a union
union NinjaData {
int i;
float f;
char str[20];
};
int main() {
// Example of a structure
struct NinjaStudent s1;
strcpy(s1.name, "Ninja1");
s1.age = 19;
s1.gpa = 8.02;
printf("Name: %s\n", s1.name);
printf("Age: %d\n", s1.age);
printf("GPA: %.2f\n", s1.gpa);
printf("Size of student structure: %ld bytes\n\n", sizeof(struct NinjaStudent));
// Example of a union
union NinjaData d1;
d1.i = 15;
printf("d1.i = %d\n", d1.i);
d1.f = 3.14;
printf("d1.f = %.2f\n", d1.f);
strcpy(d1.str, "Ninja");
printf("d1.str = %s\n", d1.str);
printf("Size of data union: %ld bytes\n\n", sizeof(union NinjaData));
return 0;
}
Output
Explanation
In the above example, we have defined a ‘struct NinjaStudent’ which contains three members: ‘name’, ‘age’ and ‘gpa’. Next, we declared a variable ‘s1’ of type ‘struct NinjaStudent’ and initialized its members, and finally printed the values of the members and size of ‘struct NinjaStudent’ type using the ‘sizeof’ operator.
Moving on, we have defined a ‘union NinjaData’ with three members: ‘i’, ‘f’, and ‘str’.We have then declared a variable ‘d1’ of ‘union NinjaData’ type and initialized its members and printed their values. We can see that when we assign a value to ‘d1.str’, the value of ‘d1.i’ and ‘d1.f’ gets lost. This happens because all three members share the same memory location.
Therefore when we print the size of Union we get 20, while when we print the size of Structure we get 60 as, 50 bytes due to the ‘name’ array + 4 bytes (‘age’ integer) + 4 (‘gpa’, which is a floating-point number) + 2 bytes of padding(it is added by the compiler and may vary depending on the specific implementation and settings of a compiler).
In a union the total size of the union is equal to the size of its largest member, therefore we got an answer as 20 bytes, as it can hold only one value at a time, storing a value in one member of the union will overwrite any previously stored values in the other members.
What is main difference between structure and union?
The main difference between a structure and a union is that a structure stores multiple data types of different sizes, while union stores multiple data types of the same size in the same location.
Is structure and union same?
Both structure and union are used to store multiple data types, but they are not the same. They differ in memory usage and data organization, a structure stores multiple data types of different sizes, while a union stores multiple data types of the same size in the same location.
Which is better structure or union?
Both structure and union have their own advantages and disadvantages. Depending on one’s specific needs, one has to decide which one to choose. Structures are used to store multiple data types of different sizes, while unions are used in optimizing memory usage by storing multiple data types of the same size in the same memory location.
What is the difference between size of structure and union?
The size of a structure is the sum of the sizes of its individual elements, while in union the size is equal to the size of its largest element. In union, all the elements share the same memory location.
Conclusion
In this article, we thoroughly discussed how structure and union are different from each other. We have understood their syntax, declaration, advantages, and disadvantages. Refer to our other articles to better understand other topics.
You will find straightforward explanations of almost every topic on this platform. You can read more such articles on our platform, Coding Ninjas Studio. So take your learning to the next level using Coding Ninjas.