What's Union And What's The Difference Between Union And Struct?
What's Union And What's The Difference Between Union And Struct?
A struct consists of one or more variables, a union consists of one variable represented in a number of different ways (a union is always the size of the largest type the variable can be stored as).
What are you mean
"a union is always the size of the largest type the variable can be stored as"?
A union can hold only one value at a time.....
i.e.
union myunion
{
int x;
float y;
};
now you can only use x or y at once...
int main()
{
myunion.x = 10;
printf("%d\n",myunion.x);
myunion.y=20.4;
printf("%f\n",myunion.y);
printf("%d",myunion.x);
return 0;
}
as you can see when you run this the value of myunion.x and myunion.y are stored in the same memory location. When you set myunion.y it overwrites myunion.x . This is a way of space saving really.The union will be the size of its largest member.
Free the weed!! Class B to class C is not good enough!!
And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi
The basic difference as stated above is that:
A struct can hold many values of many different types.
A union can hold ONE value of many different types (depending on whatever you wanted).
struct struct_tag {
int ival;
double dval;
char cval;
} stvar;
stvar can hold 3 different values ( 1x INT, 1x DOUBLE, 1x CHAR).
union union_tag {
int ival;
double dval;
char cval;
} uvar;
uvar can hold 1 value of either an integer, double, or character.