Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint

Unions

C offers a special data type, known as a union, which allows a single variable to disguise itself as several different data types. unions are declared just like structs. Here's an example:

union Number  {
    int  i;
    float f;
    char *s;
} myNumber;

This declaration creates a union type named Number. It also creates an individual Number named myNumber. If this were a struct declaration, you'd be able to store three different values in the three fields of the struct. A union, on the other hand, lets you store one and only one of the union's fields in the union. Here's how this works.

When a union is declared, the compiler allocates the space required by the largest of the union's fields, sharing that space with all of the union's fields. If an int requires 2 bytes, a float 4 bytes, and a pointer 4 bytes, myNumber is allocated exactly 4 bytes. You can store an int, a float, or a char pointer in myNumber. The compiler allows you to treat myNumber as any of these types. To refer to myNumber as an int, refer to


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial