Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

uses of unions!!!

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
i dint understand what are the applications that use unions .can somebody suggest some critical uses of unions....
 
hi cvrm

have u used cobol any time? then u must have used redefines clause in cobol. well unions are similar to redefines clause of cobol. here u can share the same memory area for different purposes.

i hope this answers ur query



icici
 
ok icici but i essentially want to know some uses of it...
ie..... u can give me some examples...where it exactly fits...
 
/*
icici's comment is correct. The classic example is creating a union
where either a number may be integer or float. In the example below
numtype is typedef'ed to be either integer or float. It's up to the
programmer to control what type is stored. Trying to output as an
integer when the last assigned value to the union was float yields
garbage.

Another real world example is:

typedef union personit {
int age;
struct {
int month;
int day;
int year;
} personrec;

In the above declaration, the personrec union holds either a single integer
representing the person's age or a structure holding the person's month,
day, and year.

Regards,

Ed

*/
#include <stdio.h>

typedef union typeit {
int intnum;
float fltnum;
} numtype;

int main()
{
numtype intoflt;

intoflt.intnum=54;

printf(&quot;integer is %d\n&quot;, intoflt.intnum);

intoflt.fltnum=3.1416;

printf(&quot;float is %f\n&quot;, intoflt.fltnum);

/* garbage from here on*/
printf(&quot;float is %d\n&quot;, intoflt.fltnum);

printf(&quot;integer is %d\n&quot;, intoflt.intnum);
}
 
Here is another application of a union that may help. Granted it will depend on endianism so the bits may be reversed

struct bitFields
{
unsigned bit0 :1;
unsigned bit1 :1;
....
unsigned bit30 :1;
unsigned bit31 :1;
};

union binNumber
{
unsigned int uvalue;
int value;
bitFields bvalue;
}


now you can do things like

binNumber b;
b.value = 17;

if(b.bvalue.bit0)
// odd value
else
// even value


All this is really showing is that you can set up bit fields to look at specific bits. There are many other applications of unions. Also, remember that the union is as large as it bigest member, and it is not a conglomeration of all the members.

Matt
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top