Solved

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

Posted on 2005-05-01
220 Views
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.

}

Regards,

Manjesh

0
Question by:Manjesh

LVL 23

Accepted Solution

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

LVL 1

Author Comment

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.

Regards,

Manjesh

0

LVL 4

Expert Comment

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

LVL 4

Expert Comment

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

LVL 1

Author Comment

I got it guys... tx for ll ur interest
0

## Featured Post

### Suggested Solutions

An Outlet in Cocoa is a persistent reference to a GUI control; it connects a property (a variable) to a control.  For example, it is common to create an Outlet for the text field GUI control and change the text that appears in this field via that Ou…
This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
The goal of this video is to provide viewers with basic examples to understand and use while-loops in the C programming language.
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.