-2

Given the following union definition:

typedef union{
int i;
char ch;
float f;}record;



record a;
//a.i = 10;
a.ch = 'A';
//a.f = 10.56;
printf("printing a.i: %p \n", a.i);
printf("printing a.ch: %c \n", a.ch);
printf("printing a.f: %f \n", a.f);
return 0;

I get the following output:

printing a.i: 65
printing a.ch: A
printing a.f: 0.000000

Why does a.i not print 0 (the default value for undefined integers) but instead the ASCII value for 'A'. Does this somehow have access to a.ch??

Jordan
  • 7
  • 2

1 Answers1

2

You get 65, the code of 'A', because field i shares a portion of its space with the char field.

Overall, though, your program’s behavior with a local union is undefined, because you read the entire int after writing only a portion of it that overlaps with the char.

Initializing the union would fix the problem. However, there is no guarantee that the read would give you 65 in the lower byte. This behavior is implementation-specific.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523