Next: Zero Length, Previous: Bit Field Packing, Up: Structures [Contents][Index]
const FieldsA structure field declared const cannot be assigned to
(see const).  For instance, let’s define this modified version of
struct intlistlink:
struct intlistlink_ro  /* “ro” for read-only.  */
  {
    const int datum;
    struct intlistlink *next;
  };
This structure can be used to prevent part of the code from modifying
the datum field:
/*phas typestruct intlistlink *. Convert it tostruct intlistlink_ro *. */ struct intlistlink_ro *q = (struct intlistlink_ro *) p; q->datum = 5; /* Error! */ p->datum = 5; /* Valid since*pis not astruct intlistlink_ro. */
A const field can get a value in two ways: by initialization of
the whole structure, and by making a pointer-to-structure point to an object
in which that field already has a value.
Any const field in a structure type makes assignment impossible
for structures of that type (see Structure Assignment).  That is
because structure assignment works by assigning the structure’s
fields, one by one.