3

Here is a union containing two types of variable int and char. If I am assign some value to int variable then what will be present in char variable?

for e.g.

union a {
  int x;
  char j;
  char k;
} ua;
int main(){
  ua.x = 0xabcd;
  printf("%x",ua.j);
}

Here what value will be printed and how?

timrau
  • 22,578
  • 4
  • 51
  • 64
Shivam
  • 211
  • 1
  • 13

2 Answers2

3

As per the C11 standard:

6.2.6 Representations of types
6.2.6.1 General
...
5 Certain object representations need not represent a value of the object type. If the stored value of an object has such a representation and is read by an lvalue expression that does not have character type, the behavior is undefined. If such a representation is produced by a side effect that modifies all or any part of the object by an lvalue expression that does not have character type, the behavior is undefined.50) Such a representation is called a trap representation.

But the lvalue expression here has char type, so this is well-defined behavior.

Also of relevance is this note from

6.5.2.3 Structure and union members:
...
95) If the member used to read the contents of a union object is not the same as the member last used to store a value in the object, the appropriate part of the object representation of the value is reinterpreted as an object representation in the new type as described in 6.2.6 (a process sometimes called ‘‘type punning’’). This might be a trap representation

What the printf statement will actually print will depend on the endianess of the system, which is to say it is implementation defined.

P.W
  • 26,289
  • 6
  • 39
  • 76
2

This code may help you to understand what is happening:

union a {
    int x;
    char j;
    char k;
}ua;

int main(){
    ua.x = 0xabcd;
    printf("%x\n",ua.x);    // Print x as hexadecimal:    abcd
    printf("%x\n",ua.j);    // Print j as hexadecimal:    ffffffcd
    printf("%x\n",ua.k);    // Print k as hexadecimal:    ffffffcd
    printf("%d\n",ua.x);    // Print x as decimal:        43981
    printf("%c\n",ua.j);    // Print j as char:           �
    printf("%c\n",ua.k);    // Print k as char:           �
}

When writting 0xabcd into an int, the memory space for the int is filled with this hexadecimal number (abcd) which value in decimal is 43981. You can print both values with %x and %d respectively.

As @Jonathan Leffler said, j and k are just different names that refer to the same byte of the union. This is why the %x prints a value finished in "cd" (the last byte of the value written, due to your system seems to use big endianness) in both cases. The "char value" is represented as � .

If you want to know why there is printed ffffff before the value, check: Printing hexadecimal characters in C.

Ganathor
  • 121
  • 1
  • 8