union

Contents

union#

If we want to use the same object, a.k.a. data storage for different datatypes, which can save memory.

#include <stdio.h>
union {
  int i;
  float f;
} number;

int main() {
  number.f = 1;
  printf("decimal: %1$d\nhexadecimal: %1$08x", number.i);
}
decimal: 1065353216
hexadecimal: 3f800000

That the output is different dependent on the data type is similar to the behavior we have seen in section Data types.

Note

You can also create a union tag or new type similar to struct.

Activity 58 (Retake: Different interpretations of a byte)

We have demonstrated different interpretations of a byte before.

  1. Recreate the same output using an union using the template below.

  2. Explain the output.

#include <stdio.h>

char data = 0b1000'0110;

// YOUR CODE HERE

int main() {
  u.data_signed = data;
  printf("%d\n", u.data_signed);
  printf("%d\n", u.data_unsigned);
  // We omit the character representation,
  // because many terminals use UTF-8 and
  // these values > 127 do not correspond
  // to a symbol in UTF-8
}

The output should be:

-122
134

Appendix#