Reputation:
I study in high school and I was making a program just to understand how a union works but the program is giving me unexpected results.
This was the program :
#include <iostream>
using namespace std;
union c{
int l;
int b;
int h;
int vol;
};
int main() {
c box;
box.l=1;
box.b=2;
box.h=3;
box.vol = box.l*box.b*box.h;
cout<<"\n Volume :- "<<box.vol;
return 0;
}
And the output was as follows :
Volume :- 27
I want to understand why this is happening.
Upvotes: 2
Views: 110
Reputation: 16331
You are having this issue because you are treating a union
as though it were a struct
.
A Union allocates a memory space that can contain any of the elements but not all of them. In the way that you have written it, there are three names that effectively point to the same address. This means that, based upon the assignments, you end up putting a 3 into the allocated space.
In other words, the way that you have written this, you have simply created four ways of referencing the same data.
An example of a way to use a union would be to describe two or more alternate structures. For example:
union Shape {
struct triangle {
int base;
int height;
}
struct rectangle {
int length;
int width;
}
}
You are now able to use a single data type to handle either case.
Upvotes: 2