Union and Struct in CPP

The size of the union will be the greatest data type inside the union and it will use that many bits to store info, while in struct the size of the struct will be the size of all the data types inside struct plus some padding. Union and Struct in CPP

Let char arr[2] will be 2 bytes info, So the compiler will use 4 bytes of info to store 2 chars and int value.

Difference between union and struct

you have to be careful that our data is not overwritten in unions.

( Yes, union allocate memory for greatest data type…. and that is int… but we haven’t assigned anything to x, then why not output is garbage in case of x ?, is everything inside a union is assigned to the value by which it(union) is initialized lastly… like in this case x automatically assigned…?)

Swap node of doubly linked list (clickhere)

Stack program in CPP (clickhere)

Abstract class in CPP (clickhere)

If you run this code

Union Program Examples in C++

#include<iostream>
using namespace std;
int main(){
union values{
int x;
char arr[2];
};

union values v;

v.arr[0] = '1'; v.arr[1] = '2';
v.x=3;
cout << v.arr[0]<<" "<<v.arr[1]<<" "<<v.x;

return 0;
}
Output:- 3

You will see the int part is taking over all the memory, the last initializing of the union will try to take over the memory.

NOW TRY TO RUN THIS CODE

What is union in C++ with example

#include<iostream>
using namespace std;
int main(){
union values{
int x;
char arr[2];
};

union values v;

v.arr[0] = '1';
cout << v.arr[0]<<endl;

v.arr[1] = '2';
cout << v.arr[1]<<endl;

v.x=3;
cout << v.x<<endl;

return 0;
}
Output

1

2

3

Union and Struct

It will print all the values, but one at a Time. Only one union member should be accessed at a time, as different variables share the same space in memory.

 

Discussion

Okay that means union allots memory of size largest data type… and if we initialize a smaller data type from union then union also assign its value to the larger data type… and the opposite is not true(if we assign a larger data type then union just initializes larger data type rest all are null)…

Ans:- You can but make sure data is not overwritten on other bits

Union and Struct in CPP
Union and Struct in CPP

END

Leave a Reply

x