Unions

Union types are derived types sharing many of syntactic and functional features of structure types. The key difference is that a union members share the same memory space.

  Note : The mikroC PRO for PIC supports anonymous unions.

Union Declaration

Unions have the same declaration as structures, with the keyword union used instead of struct:

union tag { member-declarator-list };

Unlike structures’ members, the value of only one of union’s members can be stored at any time. Here is a simple example:

union myunion {  // union tag is 'myunion'
  int i;
  double d;
  char ch;
} mu, *pm;

The identifier mu, of the type myunion, can be used to hold a 2-byte int, 4-byte double or single-byte char, but only one of them at a certain moment. The identifier pm is a pointer to union myunion.

Size of Union

The size of a union is the size of its largest member. In our previous example, both sizeof(union myunion) and sizeof(mu) return 4, but 2 bytes are unused (padded) when mu holds the int object, and 3 bytes are unused when mu holds char.

Union Member Access

Union members can be accessed with the structure member selectors (. and ->), be careful when doing this:

/* Referring to declarations from the example above: */
pm = μ
mu.d = 4.016;
tmp = mu.d;  // OK: mu.d = 4.016
tmp = mu.i;  // peculiar result

pm->i = 3;
tmp = mu.i;  // OK: mu.i = 3

The third line is legal, since mu.i is an integral type. However, the bit pattern in mu.i corresponds to parts of the previously assigned double. As such, it probably won’t provide an useful integer interpretation.

When properly converted, a pointer to a union points to each of its members, and vice versa.

Anonymous Unions

Anonymous unions are unions that are declared without tag or declarator :

union { member-declarator-list };

Such union declarations do not declare types; they declare an unnamed objects.
The name of each union member must be unique within the scope where the union is declared.

In C, an anonymous union can have a tag; it cannot have declarators. Names declared in an anonymous union are used directly, like nonmember variables.

In addition to the restrictions listed above in Union, anonymous unions are subject to additional restrictions :

Here is a simple example :

union {    // no union tag
  int i;
  float f;
  union {  // no union tag 
    unsigned char uc;
    char c;
  };       // no declarator
};         // no declarator

Anonymous Union Member Access

Anonymous union members are accessed directly because they are in the scope containing the anonymous union :

// Referring to declarations from the example above :
i = 1;
f = 3.14;
uc = 'c';
c  = 'u';
Copyright (c) 2002-2012 mikroElektronika. All rights reserved.
What do you think about this topic ? Send us feedback!
Want more examples and libraries? 
Find them on LibStock - A place for the code