Re: union



ramu said:

> Hi,
> 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?

You can only store one value in a union. Your last store was to un.j, so the
current value is a float value. If you want the union to store more than
one value at the same time, you can do that using a special kind of union
known as a struct:

#include <stdio.h> /* required because a prototype is needed for the
variadic printf function */

int main(void) /* avoid dependence on implicit int */
{
struct {
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);

return 0; /* main returns int */
}

This program gives the output you expect.


--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
.



Relevant Pages