O'Reilly logo

Just Enough C/C++ Programming by Guy W. Lecky-Thompson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Accessing Data in unions

The previous discussion relates to structs, but the data access notation for members of unions is almost identical. Recall that because the members overlap, the result is rather different.

The original union example looks like this:

union
{
    long l;
    char b[4];
} longword;

This means that you have established a definition of a union that contains four bytes, represented either as a long integer or four characters. You can now access an instance of the union as follows:

union longword uLongWord;
uLongWord.l = 1000;
printf ( "%c:%c:%c:%c",
    uLongWord.b[0], uLongWord.b[1], uLongWord.b[2], uLongWord.b[3] );

In this example, you first create the instance uLongWord and then access it as a long integer, setting the value to 1000. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required