Union u1{ int i; char c;}u2;u2.i=32767;u2.c='a';now the i value gets replaced.If we want to know the data that is saved in the union..internally, without knowing what values that we are using in the prog.that is if just want to know whether a union currently holds an int or a char? If it is a combination of both int and char..we must know even that. and the memory locations at which this data is stored?

Questions by lakshmi_pathuri

Showing Answers 1 - 2 of 2 Answers

louisYang

  • Mar 27th, 2006
 

enum with_tag {int_tag, char_tag};

 

struct with_tag{

       enum with_tag tag;

       union {

              int i;

              char c;

} twoUnion;

} sampleStruct;

 

So, when assigning new int values:

 

sampleStruct.tag = int_tag;

sampleStruct.twoUnion.i = 3;

 

when assigning new char vaules:

 

sampleStruct.tag = char_tag;

sampleStruct.twoUnion.c = 'C';

 

So, later, you can know what kind of data is assigned to union by checking tag's vaule.

  Was this answer useful?  Yes

sabarishgn

  • May 25th, 2006
 

here if suppose u.i=22;u.c='a';here i is replaced by c because in union same storage location is allocated to all fields in union.so the statement used last one is vallied i.e when we use u.c in printf statement it will display as 'a'and value of ' i ' is machine dependent.from this we can say that union can hold the variable which is used last.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions