1. Home
  2. Computing & Technology
  3. C / C++ / C#

C Programming Tutorial - Low Level Operations

By David Bolton, About.com

8 of 10

Unions- Holding Data in the Same Place

Unions

In the past we've looked at structs. To remind you a struct is a way of managing several variables in one complete "super" variable which can be assigned or copied in one statement. The definition and use of a struct is this
struct s {
  int a;
  char * b;
  int c[10];
};
typedef struct s sblock; // avoids needing the word struct!

sblock sval; // declare an instance
sval.c[4] =10; // assign a value
Download Example 5.

In a struct like the type s above, the three fields, a b and c are laid out in memory one after another. In a union though, all three fields occupy the same space.

If you know Borland/Turbo Pascal or Delphi then you may know of a variant record (nothing to do with Variant types). This is similar.

Unions are a bit of an oddity- not something you will use in everyday programming but when you need them, they are handy. Syntactically, take a struct and replace the word with union. That's it!

union u {
  int a;
  char * b;
  nt c[10];
};
Within the union u all declared fields start at the same location and the size allocated is big enough to take the largest field. The array c is ten times the size of the int a or the char * b so the structure has to big enough to take it. If the ints are 32 bits then sizeof(u) will be 40 bytes, as big as c. In any variable of type union u, assigning a value to a is the same as assigning it to b or c[0]. The space occupied by c[1] to c[9] is inaccessible and thus wasted space as far as a and b are concerned.

On the next page - Uses of unions

Explore C / C++ / C#
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C
  5. C Tutorials
  6. Unions- Holding Data in the Same Place

©2009 About.com, a part of The New York Times Company.

All rights reserved.