hi , i have a quetion on union.
union contain different data types and the one member of the union which requires highest storage will be allocated to union as in contrast to structure where the size allocated will be the sum of all the members storage requirements.
since only highest member's size is allocated to union does it mean that only one member of a union can be accessed at a time?
Hi Vins3Xtreme,
thanks for the reply.. i have a small doubt here.. i understood wat was explained in tutorial..
One of the uses a union may have is to unite an elementary type with an array or structures of smaller elements. For example:
union mix_t {
long l;
struct {
short hi;
short lo;
} s;
char c[4];
} mix;
defines three names that allow us to access the same group of 4 bytes: mix.l, mix.s and mix.c and which we can use according to how we want to access these bytes, as if they were a single long-type data, as if they were two short elements or as an array of char elements, respectively.
my doubt in above example is
1) what happens if declare 'hi' and 'lo' as long.
2) can i simultaneously access 'l' and 'hi'.
1) The example assumes that sizeof(short) == 2 and sizeof(long) == 4. That means that s and l is of the same size and take up the same memory locations. hi will be occupy the same memory as the first two bytes in l and lo, the last two bytes in l.
2) It's usually safe to do that but the C++ standard doesn't give that guarantee.
hi peter87,
can u please explain me.. how l and hi can be accessed simultaneously..
suppose i assingn l=4 and hi = 8.. what value i will be getting. or its like only one value is present in that memory location which can be accessed by different members
It depends on what endianness (byte order) your machine is using.
On little endian l=4 will write the bytes [4][0][0][0] (print the bytes in c to get this sequence) and hi is actually referring the lower bits in l so hi=8 will just change to [8][0][0][0].
On big endian machines l=4 will write [0][0][0][4]. Here hi is referring to the higher bits in l which makes me believe that the code was written for a big endian machine. hi=8 changes the first 2 bytes in c so we get [0][8][0][4].
hi peter87,
i'm still having a doubt.. suppose i have little endian byte order, then whether 'hi' wont be overwriting the value of 'l'. what if i want to access the value of l , after i assign the value of 'hi' as 8. thanks for u r reply.