Re: union



"Vladimir S. Oka" <novine@xxxxxxxxxxxxxxx> writes:
> ramu wrote:
>> main()
>> {
>> union {
>> float i;
>> int j;
>> } un;
>>
>> un.i=2.35;
>> printf("%f\n",un.i);
>>
>> un.j=3;
>> printf("%d\n",un.j);
>>
>> printf("%f\n",un.i);
>> }
>>
>> Am getting output as:
>> 2.350000
>> 3
>> 0.000000
>>
>> I wonder how it gives 0.000000 for the value of un.i when i printed
>> its value for the second time. can anyone help me out?
>
> In short (there was a more detailed discussion recently), all members of
> an union share storage. If you think in terms of memory, they are all
> stored in the same memory area (large enough to hold the largest union
> member). Writing a value into one member, and then accessing another
> will give implementation dependant results. On your implementation, it
> seems that when you read a piece of storage, with integer 3 stored in
> it, as a float, it happens you get a float 0.00000. You may have ended
> up with an illegal value of the float as well, and run into all sorts
> of problems. You were just lucky 9or knew _exactly_ waht you were
> doing).

Actually, the value is (apparently) 0.00000 within the precision
displayed by printf's "%f" format. It's probably not exactly zero.
You might try using "%g" -- or "%.20g" if you want to see even more
digits.

Also, you need to add "#include <stdio.h>" (required if you're using
printf()), "main()" should be "int main(void)", and you should have a
"return 0;" at the end.

--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
.



Relevant Pages

  • Re: union
    ... stored in the same memory area (large enough to hold the largest union ... Writing a value into one member, ... will give implementation dependant results. ... it, as a float, it happens you get a float 0.00000. ...
    (comp.lang.c)
  • Re: problem with cast and unions
    ... The part where there is that problem is about conversion from a C float ... to a Small "cell" (actually an int). ... structure, and even then, only if it was NOT the member most recently ... need to declare the union. ...
    (comp.lang.c)
  • Re: Visual C++ Express wont compare object against float in std::upper_bound
    ... Neither order compiles in Debug mode. ... The *original* order compiles in Release mode. ... operator to take two Sample arguments rather than a Sample and a float. ... operator>as member ...
    (microsoft.public.vc.stl)
  • __declspec(align(x)) and virtual tables
    ... I have a class with a virtual table that also has a member that is aligned ... __declspec) struct Vector4 {float x; ... struct MyStruct ...
    (microsoft.public.vc.language)