Ben Bacarisse
4/4/2011 9:32:00 PM
Kenneth Brody <kenbrody@spamcop.net> writes:
> On 4/3/2011 3:31 PM, Ben Bacarisse wrote:
>> DSF<notavalid@address.here> writes:
>>
>>> I have a situation where I have two structures that are identical
>>> except for the names. A simplified example:
>>>
>>> struct foo
>>> {
>>> unsigned long a;
>>> unsigned long b;
>>> };
>>>
>>> struct bar
>>> {
>>> unsigned long a;
>>> unsigned long b;
>>> };
>>>
>>> I don't have the ability to re-designate either of them, as they
>>> each belong to a different library.
> [...]
>> Can you declare a union and put both structures in it like this:
>>
>> union foobar {
>> struct foo foo;
>> struct bar bar;
>> } u;
>>
>> ? Then you can use u.foo as a struct foo and u.bar as the same data
>> interpreted as a struct bar.
>
> Technically, isn't it UB to store in one union member and then read
> from another?
The only problem is when one of the value you get is a trap and that
won't happen if the structures have the same layout (and it won't happen
if there are not trap reps regardless of layout).
A useful clarification is footnote to 6.5.2.3 p3:
If the member used to access the contents of a union object is not the
same as the member last used to store a value in the object, the
appropriate part of the object representation of the value is
reinterpreted as an object representation in the new type as described
in 6.2.6 (a process sometimes called "type punning"). This might be a
trap representation.
> Does the Standard say anything about union members
> which are identical and/or compatible? (ie: what about "int" and
> "long" members, where both are stored identically?)
If "stored identically" means (as it probably must) that they will be
aligned that same and that corresponding bits have the same meanings,
then you'll get the same value out of the long that you put into the
int.
--
Ben.