As we have already discussed, The members of the union are stored in the same memory location and the size of the whole union equals to the largest member of the Union.
So, when we find the size of the union it will return the size of the largest member of the union.
Let’s take an example for reference:
#include"iostream"
using namespace std;
union Teacher
{
int teach_id;
char teach_name[20];
float salary;
};
int main()
{
union Teacher info;
printf( "Size of Teacher id is : %d bytes\n", sizeof(info.teach_id)); // size of teach_id
printf( "Size of Teacher name : %d bytes\n", sizeof(info.teach_name)); // size of teach_name
printf( "Size of Teacher salary is : %d bytes\n", sizeof(info.salary)); // size of salary
 printf( "Size of Teacher union : %d bytes", sizeof(info)); // size of Teacher
return 0;
}
Output:
Size of Teacher id is : 4 bytes
Size of Teacher name : 20 bytes
Size of Teacher salary is : 4 bytes
Size of Teacher union : 20 bytes
Union using Pointer
Members of the Union are accessed in two ways
. (dot Operator)
-> (pointer Operator)
Accessing Members using pointer Operator
#include <iostream>
union Teacher
{
int teach_id;
char teach_name[30];
float salary;
};
int main()
{
union Teacher info;
union Teacher *ptr;
ptr = &info;
ptr->teach_id = 34;
strcpy( ptr->teach_name, "Sanya");
ptr->salary = 20000.00;
printf( "Teacher id is : %d\n", ptr->teach_id);
printf( "Teacher name is %s\n", ptr->teach_name);
printf( "Teacher salary is : %f", ptr->salary);
return 0;
}
Output :
Teacher id is : 1184645120
Teacher name is
Teacher salary is : 20000.000000