# Union tutorial

Suppose the source text looked like this:

```
#include <stdlib.h>

union urecord_t
{
  char c;
  short s;
  long l;
};

struct record_t
{
  int type;
#define RTYPE_CHAR      0
#define RTYPE_SHORT     1
#define RTYPE_LONG      2
  urecord_t u;
};

bool is_negative(record_t *r)
{
  switch ( r->type )
  {
    case RTYPE_CHAR:  return r->u.c < 0;
    case RTYPE_SHORT: return r->u.s < 0;
    case RTYPE_LONG:  return r->u.l < 0;
  }
  abort();
}
```

We have a disassembly like this:

![](https://1187734245-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FBvvTRYOmg1A3xcvtPL0T%2Fuploads%2Fgit-blob-6e8eaab6ed1971d5f0e9194fc5057f789093786d%2FBefore-1.gif?alt=media)

Let’s improve it with unions. First, let’s define an union type. Since Unions are a special case of structures, we open a structure window (menu View|Structures), press Ins to create an union. Do not check “Create Union”

![](https://1187734245-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FBvvTRYOmg1A3xcvtPL0T%2Fuploads%2Fgit-blob-0988ead5f4a2948c79990b3d63e56dc0f11ecfe8%2FDefineunion.gif?alt=media)

We create the union members using the regular data definition commands. (press D repeatedly to define a field, N to rename it) we obtain :

```
urecord_t union ;  (sizeof=0x4) chr
        db ? shrt
        dw ?
        lng dd ?
urecord_t ends;

 -----------------------------------
record_t struc ; (sizeof=0x8)
        type dd ?
        u urecord_t ?
record_t ends
```

Switching to the disassembly window (or closing the enumeration window with Alt-F3), we apply the defined structure through the **Edit|Operand types|Struct offset** menu item and select the proper representation for the operand. In the union type case, it may be necessary to select the desired union member with the **Edit|Structs|Select** union member command. The final disassembly looks like this:

![](https://1187734245-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FBvvTRYOmg1A3xcvtPL0T%2Fuploads%2Fgit-blob-e2f2d1e6fe3cf7e1973a2365d4d5a67ead3b553b%2FAfter.gif?alt=media)

That’s all folks !
