What's Union And What's The Difference Between Union And Struct?
Printable View
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.
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.
You won't encounter too many examples in programming where you need to use union. The struct and class types however are used all the time.
I agree with Witch King, I have never used Unions in my personal code. I have never really come across a situation when one would help or be needed.
It's good to know though, just in case. :D
Most sutable example is the SDL_Event union.
The interesting thing is the way they figure out what type
of event it is.
and then switching on the events' type.Code:* Keyboard event structure */
typedef struct {
Uint8 type; /* SDL_KEYDOWN or SDL_KEYUP */
Uint8 which; /* The keyboard device index */
Uint8 state; /* SDL_PRESSED or SDL_RELEASED */
SDL_keysym keysym;
} SDL_KeyboardEvent;
/* General event structure */
typedef union {
Uint8 type;
SDL_ActiveEvent active;
SDL_KeyboardEvent key;
SDL_MouseMotionEvent motion;
SDL_MouseButtonEvent button;
SDL_JoyAxisEvent jaxis;
SDL_JoyBallEvent jball;
SDL_JoyHatEvent jhat;
SDL_JoyButtonEvent jbutton;
SDL_ResizeEvent resize;
SDL_ExposeEvent expose;
SDL_QuitEvent quit;
SDL_UserEvent user;
SDL_SysWMEvent syswm;
} SDL_Event;