Reputation: 2655
I frequently define unions inside functions like this:
union
{
sometype A;
othertype B;
}name;
and then go around using them like:
name.A = smth;
name.B = smthelse;
and while it works in debug mode, in release mode it tells me that the union is uninitialized and in some places where the union members are pointers, it even crashes.So how do I initialize them?Is it sufficient to just add '=' operators?Shouldn't it have a default constructor anyway?
Upvotes: 1
Views: 1069
Reputation: 38032
From here,
You can declare and initialize a union in the same statement by assigning an expression enclosed in braces. The expression is evaluated and assigned to the first field of the union.
So, like this:
union NumericType
{
int iValue;
long lValue;
double dValue;
};
union NumericType Values = { 10 }; // iValue = 10
But it's more common (and many will say better) to do
union NumericType val; // declaration
val.dValue = 3.1415; // use union as a double
You are getting errors, because you seem to be using a union
as if it is a struct
:)
Please correct me if I'm wrong, but have a read here, for instance.
Upvotes: 1