ZetCode

K&R C unions and bit-fields

last modified December 5, 2026 K&R C 1978

Unions and bit-fields are declared like structures, but they control how values are laid out in memory. A union holds one of several types in the same storage, and a bit-field is a structure member only a few bits wide. Both expose details of the machine: the order of bytes in a word, the format of floating-point numbers, and the size of the units that hold the fields. This article uses them on GCC and on the PDP-11, where these details differ.

Unions

A union is declared with the keyword union and a list of members, like a structure. The members of a union, however, all start at the same address. The union is large enough for its largest member, and it holds a value of only one member at a time.

union.c
#include <stdio.h>

union value {
    int ival;
    double dval;
    char *sval;
};

int main()
{
    union value v;

    printf("size of the union: %d\n", (int) sizeof v);

    v.ival = 42;
    printf("ival: %d\n", v.ival);
    v.dval = 2.5;
    printf("dval: %f\n", v.dval);
    v.sval = "text";
    printf("sval: %s\n", v.sval);
    return 0;
}

union value can hold an int, a double, or a pointer to characters. Its size is the size of the double, its largest member. Each assignment replaces the previous value; the program reads back the member it has just stored. Reading a different member than the one last stored gives whatever the bits mean in the other type. Keeping track of the current member is up to the program.

$ gcc -std=c89 -pedantic -Wall -Wextra -o union union.c
$ ./union
size of the union: 8
ival: 42
dval: 2.500000
sval: text

Unions with a type field

The usual way to know which member of a union is in use is to keep a type code next to it. A symbol table of a compiler or an interpreter stores values of several types this way: each entry is a structure with a name, a type, and a union for the value.

tagged.c
#include <stdio.h>

#define INT     1
#define REAL    2
#define STRING  3

struct symbol {
    char *name;
    int type;               /* which member of u is in use */
    union {
        int ival;
        double dval;
        char *sval;
    } u;
};

struct symbol table[3];

int show(sp)
struct symbol *sp;
{
    printf("%s = ", sp->name);
    switch (sp->type) {
    case INT:
        printf("%d\n", sp->u.ival);
        break;
    case REAL:
        printf("%f\n", sp->u.dval);
        break;
    case STRING:
        printf("\"%s\"\n", sp->u.sval);
        break;
    default:
        printf("bad type %d\n", sp->type);
    }
    return 0;
}

int main()
{
    struct symbol *sp;

    table[0].name = "count";
    table[0].type = INT;
    table[0].u.ival = 12;
    table[1].name = "rate";
    table[1].type = REAL;
    table[1].u.dval = 0.25;
    table[2].name = "title";
    table[2].type = STRING;
    table[2].u.sval = "Report";

    for (sp = table; sp < table + 3; sp++)
        show(sp);
    return 0;
}

The type codes are symbolic constants. The union inside struct symbol has no tag; it is declared only as the member u, so its members are reached as sp->u.ival. show chooses the member by the type field. The table is filled with assignments, because the book gives no way to initialize a union.

$ gcc -std=c89 -pedantic -Wall -Wextra -o tagged tagged.c
$ ./tagged
count = 12
rate = 0.250000
title = "Report"

Byte order

A union of an integer and an array of characters shows how the integer is stored in memory, byte by byte. The order of the bytes is a property of the machine.

byteord.c
#include <stdio.h>

union {
    int i_val;
    char i_bytes[sizeof(int)];
} w;

union {
    long l_val;
    char l_bytes[sizeof(long)];
} lw;

int main()
{
    int k;

    w.i_val = 0x0102;
    for (k = 0; k < (int) sizeof(int); k++)
        printf("%d ", w.i_bytes[k]);
    printf("\n");

    lw.l_val = 0x01020304L;
    for (k = 0; k < (int) sizeof(long); k++)
        printf("%d ", lw.l_bytes[k]);
    printf("\n");
    return 0;
}

sizeof(int) in the array dimension makes the array as large as the integer, whatever its size. The members have prefixes, because the PDP-11 compiler requires a member name to have the same type wherever it is used, as the structures article explains. The program stores 0x0102 in an int and 0x01020304 in a long and prints the bytes in the order of their addresses. On x86-64, the least significant byte comes first, and an int has four bytes and a long eight.

$ gcc -std=c89 -pedantic -Wall -Wextra -o byteord byteord.c
$ ./byteord
2 1 0 0 
4 3 2 1 0 0 0 0 

The PDP-11 also stores the low byte of a 16-bit word first. A long, however, is two words, and the compiler puts the high word first. The bytes of 0x01020304 come out as 2 1 4 3. This mixed order is known as the PDP-11 or middle-endian byte order; programs that wrote long values to files had to swap words when the files moved to another machine.

$ cc byteord.c
$ a.out
2 1 
2 1 4 3 

Floating-point formats

A union can also show the bits of a floating-point number. Here a float shares its four bytes with two short integers, which are printed in octal.

fbits.c
#include <stdio.h>

union {
    float f;
    short w[2];
} fw;

int bits(x)
double x;
{
    fw.f = x;
    printf("%f: %o %o\n", x, fw.w[0] & 0177777, fw.w[1] & 0177777);
    return 0;
}

int main()
{
    bits(1.0);
    bits(0.5);
    bits(-2.0);
    bits(0.1);
    return 0;
}

bits stores its argument in the union and prints both words. The parameter is a double: a float argument is converted to double anyway. The mask 0177777 keeps the low 16 bits, so a negative short prints as six octal digits on both machines. On x86-64, the second word holds the sign, the exponent, and the start of the fraction of an IEEE 754 number; for 1.0 it is 037600.

$ gcc -std=c89 -pedantic -Wall -Wextra -o fbits fbits.c
$ ./fbits
1.000000: 0 37600
0.500000: 0 37400
-2.000000: 0 140000
0.100000: 146315 36714

The PDP-11 stores the word with the sign and the exponent first, and 1.0 is 040200 there, not 037600. Both formats have a sign bit, eight bits of exponent, and a fraction whose leading 1 bit is not stored. The PDP-11, however, reads the fraction as a number between 0.5 and 1 and adds 128 to the exponent, while IEEE 754 reads it as a number between 1 and 2 and adds 127. The same bits mean different numbers on the two machines, so binary floating-point data could not move between them without conversion. 0.1 has no exact binary value in either format; the low word holds the end of the rounded fraction.

$ cc fbits.c
$ a.out
1.000000: 40200 0
0.500000: 40000 0
-2.000000: 140400 0
0.100000: 37314 146315

Bit masks

Several yes-or-no values fit into one integer, one bit each. A compiler might keep the properties of a name this way. Each property is a constant with one bit set, and the bitwise operators set, clear, and test them.

masks.c
#include <stdio.h>

#define KEYWORD     01
#define EXTERNAL    02
#define STATIC      04

int show(flags)
int flags;
{
    printf("%o:", flags);
    if (flags & KEYWORD)
        printf(" keyword");
    if (flags & EXTERNAL)
        printf(" external");
    if (flags & STATIC)
        printf(" static");
    printf("\n");
    return 0;
}

int main()
{
    int flags;

    flags = 0;
    flags |= EXTERNAL | STATIC;         /* turn two bits on */
    show(flags);

    flags &= ~STATIC;                   /* turn one bit off */
    show(flags);

    flags ^= KEYWORD | EXTERNAL;        /* flip two bits */
    show(flags);

    if ((flags & (EXTERNAL | STATIC)) == 0)
        printf("neither external nor static\n");
    return 0;
}

The constants are written in octal, which makes the bits easy to see: 01, 02, and 04 are the three lowest bits. flags |= EXTERNAL | STATIC sets two bits, flags &= ~STATIC clears one, and ^= flips bits. flags & (EXTERNAL | STATIC) is zero only if both bits are clear; the parentheses around the comparison are required, because == binds more tightly than &.

$ gcc -std=c89 -pedantic -Wall -Wextra -o masks masks.c
$ ./masks
6: external static
2: external
1: keyword
neither external nor static

Bit-fields

A bit-field is a structure member with a width in bits, written after a colon. Fields are declared unsigned, and adjacent fields are packed into the same machine word. The program of the previous section can then name its flags instead of masking them.

fields.c
#include <stdio.h>

struct {
    unsigned is_keyword : 1;
    unsigned is_extern  : 1;
    unsigned is_static  : 1;
} flags;

int show()
{
    printf("keyword %d, extern %d, static %d\n",
        flags.is_keyword, flags.is_extern, flags.is_static);
    return 0;
}

int main()
{
    flags.is_extern = flags.is_static = 1;
    show();

    flags.is_static = 0;
    show();

    flags.is_keyword = !flags.is_keyword;
    flags.is_extern = !flags.is_extern;
    show();

    if (flags.is_extern == 0 && flags.is_static == 0)
        printf("neither external nor static\n");
    printf("size of flags: %d\n", (int) sizeof flags);
    return 0;
}

Each flag is a field one bit wide, and it is used like a small integer member: flags.is_static = 0 clears the bit, and the tests need no masks. A field has no address, so & cannot be applied to it, and there are no arrays of fields. The three fields fit into one unsigned, which takes 4 bytes on x86-64.

$ gcc -std=c89 -pedantic -Wall -Wextra -o fields fields.c
$ ./fields
keyword 0, extern 1, static 1
keyword 0, extern 1, static 0
keyword 1, extern 0, static 0
neither external nor static
size of flags: 4

On the PDP-11 the same structure takes one 16-bit word.

$ cc fields.c
$ a.out
keyword 0, extern 1, static 1
keyword 0, extern 1, static 0
keyword 1, extern 0, static 0
neither external nor static
size of flags: 2

Packed data

Fields wider than one bit pack small numbers. A date fits into 16 bits: 5 bits for the day, 4 for the month, and 7 for the year counted from 1900. A union with an unsigned shows the packed word.

packed.c
#include <stdio.h>

/* a date in one 16-bit word: day 1-31, month 1-12, year since 1900 */
struct date {
    unsigned d_day   : 5;
    unsigned d_month : 4;
    unsigned d_year  : 7;
};

union {
    struct date d;
    unsigned word;
} u;

int main()
{
    u.word = 0;
    u.d.d_day = 5;
    u.d.d_month = 12;
    u.d.d_year = 78;
    printf("%d.%d.%d\n", u.d.d_day, u.d.d_month, 1900 + u.d.d_year);
    printf("word: %o\n", u.word);

    /* the same fields with shifts and masks */
    printf("%d.%d.%d\n", u.word & 037, (u.word >> 5) & 017,
        1900 + ((u.word >> 9) & 0177));

    u.d.d_year += 50;               /* 128 does not fit in 7 bits */
    printf("year: %d\n", 1900 + u.d.d_year);
    return 0;
}

The word is cleared first, so that no bits outside the fields are left over. The fields are allocated from the low bits of the word on both machines: the day takes bits 0–4, the month bits 5–8, and the year bits 9–15. Shifts and masks extract the same values from the word, which is how the fields are implemented. A field is an unsigned number of its width: 78 + 50 does not fit into 7 bits, and the year wraps around to 0.

$ gcc -std=c89 -pedantic -Wall -Wextra -o packed packed.c
$ ./packed
5.12.1978
word: 116605
5.12.1978
year: 1900

Fields are unsigned

The book says that fields are unsigned, whether they are declared int or unsigned, and the PDP-11 compiler treats them so. GCC treats an int field as signed, so the two compilers read the same field differently.

sfields.c
#include <stdio.h>

struct {
    int small : 3;
    unsigned tiny : 3;
} f;

int main()
{
    int n;

    for (n = 5; n <= 8; n++) {
        f.small = n;
        f.tiny = n;
        printf("%d: small %d, tiny %d\n", n, f.small, f.tiny);
    }
    return 0;
}

Both fields are three bits wide. GCC stores 5, 6, and 7 in the int field as the bit patterns 101, 110, and 111 and reads them back as negative numbers; the unsigned field holds 0 to 7. In both, 8 needs a fourth bit and leaves 0.

$ gcc -std=c89 -pedantic -Wall -Wextra -o sfields sfields.c
$ ./sfields
5: small -3, tiny 5
6: small -2, tiny 6
7: small -1, tiny 7
8: small 0, tiny 0

The PDP-11 reads both fields as unsigned numbers. A portable program declares its fields unsigned.

$ cc sfields.c
$ a.out
5: small 5, tiny 5
6: small 6, tiny 6
7: small 7, tiny 7
8: small 0, tiny 0

Source

Dennis Ritchie: C Reference Manual (1975)

GCC: Structures, Unions, Enumerations, and Bit-Fields

In this article we have used unions and bit-fields in K&R C: unions and their size, a union with a type field, the byte order and floating-point formats of x86-64 and the PDP-11, flags kept with bit masks and with bit-fields, packed data, and the unsigned fields of the PDP-11. The next article splits programs into several files: program structure.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all K&R C tutorials.