Neo said:
Neo said:
Hi,
U can do it like this also :
union ABYTE {
char ch;
int i;
} aByte;
int main()
{
aByte.i = 1;
if(aByte.ch)
Whether or not that works, is implementation defined.
N869
6.5.2.3 Structure and union members
[#5] With one exception, if the value of a member of a union
object is used when the most recent store to the object was
to a different member, the behavior is
implementation-defined.
If it's not permissible to write to one member of the Union and read back
from another member of the Union, what is the use of the a UNION then? I
think this one the most common uses of a UNION, isn't it?
Nope. The most common use is to confuse people who do not think
things through ;-)
In a structure, you gather data which belongs together logically
and has to be present all at once. In a union, you store data
which is logically equivalent but the situations where union members
are used are mutually exclusive.
Example:
union {
double binaryfraction;
struct {
int numerator;
int denominator;
} symbolicfraction;
} fraction;
If you are in the symbolic context, you use the symbolicfraction
and do not lose anything; if the symbolic fractions no longer can
express the numbers, you go over to floating point numbers. As both
representations at once would waste memory, you just put them
together. Now, you only have to mind the context... (see below)
.... which is provided for by the above.
union {
struct {
int type;
} generic;
struct {
int type;
double fpdata;
} binaryfraction;
struct {
int type;
int numerator;
int denominator;
} symbolicfraction;
} fraction;
Now, you can also store the type of fraction within the union, access
it via generic.type and will automatically know binaryfraction.type
and symbolicfraction.type, as it has to be the same.
With the right sort of access macros (one set for reading, one for
writing), this is still manageable.
If you use a union to access some "bit pattern" by different data types,
you can run into different problems:
- trap representations: There are bit patterns which are not valid
for one type but for the other.
- the compiler optimised access to a certain union member by putting
it or parts of it into registers and if you access another union
member, you will not work with the actual representation but the
last stored.
- ... (too lazy to list all I can think of
)
Cheers
Michael