Okay so i'm reading through my programming book and come back across the forgotten union. I'm sitting here reading it thinking, when, at least in console based c++ are unions actually useful? I can understand them if you have a huge program that accesses memory alot, but this doesn't seem feasible at least in the console. Can anyone provide a decent example of when this might actually be used?
Unions are very useful. Just an example: you can define a bitfield of 8 bits and a byte declared as unsigned char. Put those two in an union and then you can assign a received byte to the byte in the union and with the bitfield in the union you can access the bits individually.
In some cases it is useful when you want to decrease the amount of used memory. If you have to use an int in the first part of the function and a char in the second part. Then you can declare two variables, one of type int and one of type char, but you could also introduce an union. Ofcourse this is only useful if the first variable isn't used anymore before using the second.
A use of unions doesn't necessarily involve needing hteme only when a program gets big, actually its just smart use of memory through an entire program. A good example would be that for different screen modes a Pixel may be a different lenth of memory, fo example:
However I rarely use them, only because of the ability templates gives you however.
unsigned char Eightbit;
unsigned short Sixteenbit;
unsigned long ThirtyTwobit;
if(screenmode == 8)
pixel.eightbit = color8;
if(screenmode == 16)
pixel.Sixteenbit = color16;
if(screenmode == 32)
pixel.ThiryTwobit = color32;
I wrote a program that creates some binary code at runtime....it then creates a thread and runs the code I created.......
In calculating jumps for the function calls I had to address 32 bit variables on a byte by byte basis......
So when I had my 32bit address I stored it in a union like so;
Then by switching the member to the 1 byte member I could assign a pointer to a UCHAR and I was away!
UINT uiMemPos; //32 bit
UCHAR ucMemPos; // 8 bit
Dont know if this was the best way to do this......but it worked pretty well........
I dont define unions much at all (though I use them occasionally in preconfigured structures).......they are just a tool worth knowing about for certain situations