Union-Data sharing

A union is a type that can share multiple data. Sharing means that member variables use the same memory area. Unions can be used in the same way as structures, except that they share data.

#include <stdint.h>

// Union type
union myapp_value {
  int8_t i8_val;
  int16_t i16_val;
  int32_t i32_val;
  int64_t i64_val;
  float float_val;
  double double_val;
  void * ptr_val;
};;

Member variables share one memory area. This means that only one can be used at a time.

The size of the union returned by the sizeof operator is the largest member variable sizeof operator sizeof operator < It is the size returned by / a>.

Use of unions

Let's use a union. Unions are available as types. The union is declared, the value is assigned to the member variable, and the contents are output.

#include <stdint.h>
#include <stdio.h>

// Definition of a union that represents book information
union myapp_value {
  int8_t i8_val;
  int16_t i16_val;
  int32_t i32_val;
  int64_t i64_val;
  float float_val;
  double double_val;
  void * ptr_val;
};;

int main (void) {
  // Union variable declaration
  union myapp_value value;
  
  // Assign a value to the member variable i32_value
  value.i32_val = 4;
  printf("i32_val:%d\n", value.i32_val);
  
  // Assign a value to the member variable double_val
  value.double_val = 2.56;
  printf("double_val:%f\n", value.double_val);

  // Oh, the value of i32_val has been updated
  printf("i32_val:%d\n", value.i32_val);
  
  // Union size
  printf("size of union mypp_value:%d\n", sizeof (union myapp_value));
}

What is the union for?

This is to save memory area.

"Well, that's it?"

Yes. There are times when you really want to save memory for optimization, and use that.

Saving memory has a positive effect on performance as it increases memory locality.

Associated Information