Click here to Skip to main content
15,891,253 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
We know that in Union only memory location is allocated for all variable and at a time only one variable can be stored in memory.
Can we find out which member variable is presently stored in memory without using seperate flags?

suppose we have an union
C++
union cde
{
    char c;
    int d;
    float e
}


Now here how to find out which member variable is presently stored in memory?
Assume that the member variables have garbage values in them.
Posted

You can't say which variable is currently stored in memory, they all are, but at the same location; if you change c, then d and e will change too.

Some more info on unions; http://www.cplusplus.com/doc/tutorial/other_data_types/[^].
 
Share this answer
 
v2
Comments
rupeshkp728 13-Nov-11 15:11pm    
Thanks for the clarification.
Sergey Alexandrovich Kryukov 13-Nov-11 16:11pm    
Correct, a 5.
--SA
Albert Holguin 13-Nov-11 18:26pm    
+5... unions are pretty straight forward, but I guess the idea is sort of abstract for some
Boy, you are full of strange questions today.

A union allows you to interpret a "sequence of bits and/or bytes" in multiple ways. It cannot hold multiple variables but you can look at the single contents as if it were different things.

Sometimes it doesn't make any sense to do so, as in your example. Sometimes the union is part of a larger record that has the typing field so you know exactly how to interpret.

Without typing flags, you cannot really tell one kind from another. Oh, you can make some guesses based on bit patterns but, in reality, you cannot tell really small floating numbers from large integer values and just about any 8 bit sequence can be a character string so unless you're looking for words in a particular language, you cannot tell.
 
Share this answer
 
Comments
rupeshkp728 13-Nov-11 15:32pm    
Thanks Chuck for the reply.
Sergey Alexandrovich Kryukov 13-Nov-11 16:11pm    
Very clear, my 5.
--SA
Albert Holguin 13-Nov-11 18:25pm    
This is a pretty strange question indeed... +5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900