Structure Vs Union

Status
Not open for further replies.

Mohan Giri

In Runtime
Messages
144
What is the difference between structure and union?? Where we use structure data type and where we use union data type?
 
a structure and a union differs in the memory allocation
a union takes the highest type of the variable allocated.
for example....
union u1{
int rolno;
char name;
};

then the maximum abt of memory will be that as the size of the integer....

but in the case of the structure,
struct s2{
int rollno;
char name;
};
the memory allocation will be that of a char and a int
thats the plain difference between the two.....
 
Warrior is right. If it wasn't clear, with a structure, what he meant was that the total memory allocated will be sizeof(int) + sizeof(char)..

In anycase, why are unions useful?.. Well, one application would be if u want to easily "go through" a variable. For example, in the example above, if the "int" has a particular value that u had set, using a "char" array variable would allow u to obtain a byte from the int without having to worry about bit shifting/masking/pointers and such..
 
Status
Not open for further replies.
Back
Top Bottom