Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Consecutive bit-field members are allocated by the compiler to the same int-sized word, as long as they fit completely. ThusConsequently, on a 32-bit machine, a TIME_DAY object will occupy occupies exactly one {int}}-sized word. On a 16-bit machine, the first five members (totalling 16 bits) will fit into one int-sized word, and the last four members will fit into an immediately following word. Such an exact fit is rare, however. Add another member such as "day-of-year" to the structure, and the nice size-fitting property disappears. ThusConsequently, bit-fields are useful for storage-saving only if they occupy most or all of the space of an int, and if the storage-saving property is to be reasonably portable, they must occupy most of the space in a 32-bit integer 6-1.

The order of allocation within a word is different in different implementations. Some implementations are "right-to-left": the first member occupies the low-order position of the word. Most PDP-11 and VAX compilers allocate right-to-left. Following the convention that the ]owlow-order bit of a word is on the right, the right-to-]eft left allocation would look like this:

...

A union provides a convenient way to say what is going on:

Code Block

typedef union time_overlay {	/* MACHINE DEPENDENT */

...


  struct time_day time_as_fields;

...


  long time_as_long;

...


} TIME_OVERLAY;

...



TIME_OVERLAY time_port;

This allows bitwise operations like time_port.time_as_long & 0xF00 as well as providing access via bit-field names like time_port.time_as_fields.h1.

Specifying a field size of zero causes any subsequent allocations to begin on a new word boundary. Un-named bit-fields are allowed; they occupy space but are inaccessible, which is useful for "padding" within a structure.

Because most C machines do not support bit-addressing, the "address-of" (&) operator is not allowed upon bit-field members.
Aside from these complications, bit-fields can be treated just like any other structure member. The following declaration

...

tests whether now is less than " noon."
If we wish to use the TIME_DAY structure for an " information-hiding " purpose, so that it could be changed without affecting the programs that use it, we should employ the "leading-underscore" convention mentioned earlier in Section 6.2 :

...