+ 1
I'm confused in c++ union.
In the given code. I had define three variables in union. Why is that when I assign only two variables. That is int and char. It's giving perfect values!!! But when I try to assign value of float. It gives garbage value. Why is that? I'm so confused in union. https://sololearn.com/compiler-playground/cCckTgB9sghk/?ref=app
9 Answers
+ 4
the cout is immediately after the assignment.
put all the cout below, then you'll see how other values becomes wrong. It's always the last assignment that's correct and useful.
#include <iostream>
using namespace std;
union money
{
/* data */
int rice;
char car;
float pounds;
};
int main()
{
union money m1;
m1.rice = 34;
cout << m1.rice << endl; // correct
m1.car='A';
cout << m1.car << endl; //correct
m1.pounds = 0.215;
cout << m1.pounds << endl; //correct
cout << m1.rice << endl; // wrong
cout << m1.car << endl; //wrong
return 0;
}
+ 2
#include <iostream>
using namespace std;
union money
{
/* data */
int rice;
char car;
float pounds;
};
int main()
{
union money m1;
m1.rice = 34;
cout << m1.rice << endl;
m1.car='A';
cout << m1.car << endl;
m1.pounds = 0.215;
cout << m1.pounds << endl;
return 0;
}
+ 2
no.
a struct is a collection.
a union is a single value.
a struct is an 'all of' collection.
a union is an 'any one of' type.
it's a "choose one of the provided" value.
only the last one assigned is correctly retrievable.
it's a workaround for an 'any' type variable.
+ 2
Bob_Li
Oh got it thanks!!
+ 1
where's your code?
+ 1
Bob_Li Thanks. It seems to work perfectly fine. But exactly if differs from struct? Both of them seemed to do same job.
+ 1
the union can only correctly represent one value at a time.
in your example, you assigned char after int, that's why your int became 65. it's the int value of A
+ 1
Bob_Li
I assigned char after int. That's why my int became 65.
But in your code, When you assigned everything perfectly. It seems to work fine. Like int value was displaying 34.
And it was giving output of struct.
Why is that?(sorry for asking stupid questions. I'm revising c++ after 3 years)
0
Bob_Li Attached..