What is a union?

A union, is a collection of variables of different types, just like a structure. However, with unions, you can only store information in one field at any one time.
You can picture a union as like a chunk of memory that is used to store variables of different types. Once a new value is assigned to a field, the existing data is wiped over with the new data.

Declaring a union

Declaring a union is exactly the same as declaring a struct, except you use the union keyword:

union human { 
  char *name; 
  int age; 
  float height; 
}; /* don't forget this semi colon!!!! */ 

Once again, you can use a typedef statement to simply the declaration of union variables.

The size of an union is the size of its largest field.
#include <stdio.h>
typedef struct robot1 ROBOT1;
typedef union  robot2 ROBOT2;
struct robot1 {
 int ammo;
 int energy;
};
union robot2 {
 int ammo;
 int energy;
};
int main() {
  ROBOT1 red = {10,200};
/* ROBOT2 blue   = {15,100};  DOESN'T WORK WITH UNIONS  */ 
  ROBOT2 blue;
  blue.ammo = 15;
  blue.energy = 100;
  printf("The red robot has %d ammo ", red.ammo);
  printf("and %d units of energy.\n\n", red.energy);
  printf("The blue robot has %d ammo ", blue.ammo);
  printf("and %d units of energy\n.", blue.energy);
  return 0;
}

Output:
The red robot has 10 ammo and 200 units of energy.

The blue robot has 100 ammo and 100 units of energy.

#include <stdio.h>
typedef union robot ROBOT;
union robot { 
  char *name; 
  int energy; 
};
int main() {
  int i;
  ROBOT robots[3];
  robots[0].name = "Lunar Lee";
  robots[0].energy = 50;
  robots[1].name = "Planetary Pete";
  robots[1].energy = 20;
  robots[2].name = "Martian Matt";
  robots[2].energy = 30;
  for(i=0 ; i<3 ; i++) {
    /*printf("Robot %d is called %s ", i, robots[i].name);*/
    printf("and has %d units of energy.\n", robots[i].energy);
  }
  return 0;
}

Output:
and has 50 units of energy.
and has 20 units of energy.
and has 30 units of energy.

Back