I have the basic idea about structure and union.but I found some codes, that using structure inside union , union inside structure, insdie a structure a union and again one more structure inside the same union.
So,where union inside structure is used? what is the advantage for it?
Combining a structure within a union can streamline code generation.
You must be aware of the endianness of the compiler and/or device.
An example of the techniques use for ADC values:
Code:
union ADCvalue {
unsigned int EntireWord;
struct bytes {
unsigned char MSB;
unsigned char LSB;
}
}
union ADCvalue ADCval;
int ADCResult ;
ADCval.bytes.MSB = ADRESH; // retrieve and store ADC's MSB
ADCval.bytes.LSB = ADRESL; // retrieve and store ADC's LSB
ADCResult = ADCval.EntireWord; // retrieve 16bit result
Of course, depending on the endianness of the compiler and/or device, if applicable, you may need to reverse the order of MSB and LSB within the structure definition.
Another typical application is the requirement to access both the entire value, collection of bits or single bits of a register, such as various device specific header files utilized by compilers.