Examples of Union in C [closed]

I'm looking for some union examples, not to understand how union works, hopefully I do, but to see which kind of hack people do with union.

So feel free to share your union hack (with some explanation of course :) )


One classic is to represent a value of "unknown" type, as in the core of a simplistic virtual machine:

typedef enum { INTEGER, STRING, REAL, POINTER } Type;

typedef struct
{
  Type type;
  union {
  int integer;
  char *string;
  float real;
  void *pointer;
  } x;
} Value;

Using this you can write code that handles "values" without knowing their exact type, for instance implement a stack and so on.

Since this is in (old, pre-C11) C, the inner union must be given a field name in the outer struct. In C++ you can let the union be anonymous. Picking this name can be hard. I tend to go with something single-lettered, since it is almost never referenced in isolation and thus it is always clear from context what is going on.

Code to set a value to an integer might look like this:

Value value_new_integer(int v)
{
  Value v;
  v.type = INTEGER;
  v.x.integer = v;
  return v;
}

Here I use the fact that structs can be returned directly, and treated almost like values of a primitive type (you can assign structs).


Unions are also commonly used in the lexical analysis and parsing stage of language processors, like compilers and interpreters. Here is one I'm editing right now.

union {
    char c;
    int i;
    string *s;
    double d;
    Expression *e;
    ExpressionList *el;
    fpos_t fp;
}

The union is used to associate semantic values with the tokens of the lexical analyzer and the productions of the parser. This practice is quite common in grammar generators, like yacc, which provides explicit support for it. The union can hold any of its values, but only one of them at the time. For instance, at any one point from the input file you've either read a character constant (stored in c), or an integer (stored in i) or a floating point number (stored in d). The grammar generator provides considerable assistance for determining which of the values is stored at any one time depending on the rule being processed.