Re: union
- From: Richard Heathfield <invalid@xxxxxxxxxxxxxxx>
- Date: Tue, 31 Jan 2006 07:49:00 +0000 (UTC)
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)
.
- References:
- union
- From: ramu
- union
- Prev by Date: Re: union
- Next by Date: Re: What u mean by this statemnet ?.
- Previous by thread: Re: union
- Next by thread: What u mean by this statemnet ?.
- Index(es):
Relevant Pages
|