2.10. Union Types

A union type is similar to a structure. But all of the variables listed in the union are stored starting at the beginning of the union's memory. So they overlap in memory, and you can only store one of them at a time.

For example,

  union intOrReal
  {
    int    n;
    double x;
  };
defines type union intOrReal.

You will probably prefer to give it a name, as

  typedef union intOrReal
  {
    int    n;
    double x;
  }
  INT_OR_REAL;

If u has type INT_OR_REAL then u.n is the integer value of u and u.x is the real value.

C provides no way for you to determine which value is stored in a union type. It is up to you to know that.