From: Francis Glassborow on
krishna wrote:
> int main()
> {
> union my_union{
> int i;
> float f;
> };
> my_union u;
> u.f = 2.0;
> std::cout << u.i;
> }
>
> why is int casted value of u.f not given? (the start address is the
> same for all the members).
>
> -Krishna.
>

FOFL
That is not how unions work. They are a way of recycling memory and at
any one time the bit pattern stored in one represents exactly one of the
fields. Trying to read a union through a different field than the one by
which it was written is strictly undefined behaviour (there are some
special cases which are exceptions) What you did was to initialise u as
a float and then try to read it as an int. Officially the program can do
anything, in practice (in this case) it will probably just reinterpret
the stored bit pattern (as many bits as it needs) as an int. If the
result happens to be a trap value then your program may stop.

--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

From: George Neuner on
On Mon, 9 Nov 2009 14:01:56 CST, Francis Glassborow
<francis.glassborow(a)btinternet.com> wrote:

>krishna wrote:
>> int main()
>> {
>> union my_union{
>> int i;
>> float f;
>> };
>> my_union u;
>> u.f = 2.0;
>> std::cout << u.i;
>> }
>>
>> why is int casted value of u.f not given? (the start address is the
>> same for all the members).
>>
>> -Krishna.
>>
>
>FOFL
>That is not how unions work. They are a way of recycling memory and at
>any one time the bit pattern stored in one represents exactly one of the
>fields. Trying to read a union through a different field than the one by
>which it was written is strictly undefined behaviour (there are some
>special cases which are exceptions) What you did was to initialise u as
>a float and then try to read it as an int. Officially the program can do
>anything, in practice (in this case) it will probably just reinterpret
>the stored bit pattern (as many bits as it needs) as an int. If the
>result happens to be a trap value then your program may stop.

It should be noted that, while C++ does not define the result, unions
are used in this way to pass binary floating point data between CPUs
with opposite endianess.

But pretty much any usage other than such deliberate data conversion
is asking for trouble.

George

--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]