In most of the programming languages like C and C++, structure and union are user-defined data types used to create a set of desired results. Let us understand the difference between these two in this article clearly.
A structure is a user-defined data type. Structures are used to represent data items of different kinds under one single entity. This means a structure can hold data items of different kinds and store them as a record.
The variables in a structure are called its members. To declare a structure, the keyword struct is used before the name of the structure. This informs the compiler that a structure has been created.
Here, we declare a structure for storing the information of the students. The name of the structure is the name of the data type that has been created. In this case, the name of the structure is Student.
Student s1, s2;
This is how the variables of student type are created. To add data in these variables we use the dot(.) operator.
s1.name = “Maya”;
s1.roll_no = 2;
s1.grade = 5;
Here is a code for a better understanding:
using namespace std;
cout<<"Enter the student name: ";
cout<<"Enter student roll number: ";
cout<<"Enter students marks: ";
cout<<"The information you have entered is: \n";
cout<<"Student name: "<<sdt.name<<endl;
cout<<"Student Roll No. is: "<<sdt.roll_no<<endl;
cout<<"Student marks: "<<sdt.marks<<endl;
In the above case, we enter all the values, and the output gives the result of each value being accessed at the same time. Thus, a student data type is created that can help us to store the records of various students.
A union is also a user-defined data type that is used to store the information. However, in a union, the memory is allotted only once, and therefore, all the members of a union store the same value.
The declaration of a union and a structure are the same. The only difference is that of a keyword. A union is preceded by the keyword union.
Here, we declare a union for storing the information of the students. The name of the union is the name of the data type that has been created. In this case, the name of the union is Student. The variables of this type can be created similar to that of a structure.
Student s1, s2;
This is how the variables of student type are created. Like a structure, the accessing of data is done with the help of the dot(.) operator. However, in a union, the one-time initialization of data is not possible.
This means that if the value of one data member is altered it will affect the values of other data members as well. Moreover, the size of the union is equal to the size of the largest member of that union.
For the considered example, the space allocated to ‘char’ is 1 byte, and that to ‘int’ is 4 bytes, so, the largest size is 4 bytes. Hence, the memory allotted to ‘s1’ and ‘s2’ is 4 bytes each.