• Status: Solved
• Priority: Medium
• Security: Public
• Views: 230

How to find out which element of Union is valid ?????

Hi All,
This is very basic question, I agree, but i could not find the answer for this. So experts pardon me.

In have a union named,

union temp_union
{
char ch;
int i;
};

and a function called

showunion(temp_union* tu)
{
// I need to check for the valid element and display the element.
// It might be a character or a Integer, So how can i extract the valid element from the union.

}

Thanks for your earliest attention.

Regards,

Manjesh

0
Manjesh
1 Solution

Commented:
Usually a separate type code is stored somewhere that provides a
clue to which element of the union is valid.  Often these are combined
into a structure as follows:

enum utype { CharType, IntType, FloatType, DoubleType };

struct {
enum utype type;      // what type is this thing?
union value {
char ch;
int i;
float f;
double d;
} val;
} x;

switch (x.type) {
case CharType:      use(x.val.ch); break;
case IntType:            use(x.val.i); break;
case FloatType:      use(x.val.f); break;
case DoubleType:      use(x.val.d); break;
}

0

Author Commented:
well .. thats a good piece a code, which will serve my purpose.

But , I would like to know does "C" by itself provide any mechanism to fnd out the valid element in union.

Because if I have 100 elements in union, I need to write switch case for 100 variables.

Thanks for your earliest attention.

Regards,

Manjesh

0

Commented:
Hi Manjesh,

agree with brett, union is just a chunk of memory as large as the largest union member. all shorter members are stored from the beginning of the union leaving the rest untouched (thus if some data were there before, they'll be not erased). there's no way of telling the actual type of the union except storing it in separate variable.

Cheers!
0

Commented:
Every union member is pointing to same memory location(starting location of uion variable). That's why sizeof union variable is biggest size of its data member. So, you can't detect valid data member. Every variable has the value, but you can't judge which one has the valid value you want.
-Mahesh
0

Author Commented:
I got it guys... tx for ll ur interest
0

Featured Post

Tackle projects and never again get stuck behind a technical roadblock.