Emman
Emman

Reputation: 1244

Why garbage value in union integer?

For the below program int is printed with garbage value but expected is the initialized value 50, Is there any specific reason for this value at the output?

#include <stdio.h>
#include <string.h>

union data
{
    int a;
    float c;
    char b[10];
};

int main()
{
    union data x;
    x.a = 50;
    strcpy(x.b,"hello");
    x.c = 21.50;
    printf ("x.a:= %d\n",x.a );
    printf ("x.b:= %s\n",x.b );
    printf ("x.c:= %f\n",x.c );
    return 0;
}

Output:

x.a:= 1101791232
x.b:= 
x.c:= 21.500000

Update: For similar program as mentioned below everything work fine, I have no clues how this could produce the expected results

#include <stdio.h>
#include <string.h>

union Data
{
   int i;
   float f;
   char  str[20];
};

int main( )
{
   union Data data;        

   data.i = 10;
   printf( "data.i : %d\n", data.i);

   data.f = 220.5;
   printf( "data.f : %f\n", data.f);

   strcpy( data.str, "C Programming");
   printf( "data.str : %s\n", data.str);

   return 0;
}

Output :

data.i : 10
data.f : 220.500000
data.str : C Programming

Upvotes: 1

Views: 1890

Answers (2)

dtech
dtech

Reputation: 49319

A union will use the same storage location for all its members. You set x.a but then when you set x.c it overwrites the memory location of x.a as well.

In binary, the integer value 1101791232 is the same as the float value 22.50, and you can easily verify that:

  float f = 21.50;
  int * iP = (int*)&f;
  cout << *iP;

The union data looks something like this in memory (each X is a byte):

XXXXXXXXXX <- union data
XXXX       <- int a
XXXX       <- float c
XXXXXXXXXX <- char b[10]

So writing to a or c will overwrite the other, plus the first 4 elements of the char array.

As for your second example, try setting the three members and only afterwards output their values, and they will be garbage again. It only works because you output immediately after setting and before overwriting.

Upvotes: 4

Benjy Kessler
Benjy Kessler

Reputation: 7656

The whole point of unions is that setting one value overrides all other values.

The last thing you set in the union is c=21.50. The value of a will then be the bits of 21.50 as if they represented an int.

The value of 21.50 is 0x41ac0000 (see float to hex converter) which casted to int happens to be 1101791232 (see hex to decimal converter).

Upvotes: 4

Related Questions