Duane said:
I've heard this before but you mean basically that:
Well, I think what Ron said was somewhat confusing. I already quoted the
C standard on the issue. It's implementation-defined, that means that
the standard doesn't impose any behavior, but the implementation has to
select a behavior and document it. So the behavior for a user is not
unspecified, you can check your documentation.
There's also the bit about the union members being structs with common
initial sequences.
union spoo {
unsigned char c[sizeof(short)];
short s;
};
spoo doh;
doh.c[0] = LOW_BYTE;
doh.c[1] = HIGH_BYTE;
cout << doh.s ;
is undefined?
Not in C. Some have said that is so in C++, but I haven't seen a quote
from the standard. Usually these things are the same between the
languages, but sometimes not. Obviously, the fact that all data is POD
in C but not in C++ may well be a factor.
This is a common method to interpret unsigned char
data from I/O devices. I know it can be done without
a union but not as cleanly. I don't see how this could
not work (as long as you are aware of the endianness
of the unsigned chars etc.)
It likely would. That doesn't mean it's guaranteed. You can do the same
thing by casting a pointer to the object to a pointer to unsigned char,
then access the bytes that way. That is standard.
Any thoughts? At any rate, what would be the purpose
of a union?
These days, very little. I haven't used a union in anger since the DOS
days.
Brian Rodenborn
Brian Rodenborn