Complying with standard C

Type qualifiers in derived types

The type qualifiers are unique in that they may modify type names and derived types. Derived types are those parts of C's declarations that can be applied over and over to build more and more complex types: pointers, arrays, functions, structures, and unions. Except for functions, one or both type qualifiers can be used to change the behavior of a derived type.

For example:

   const int five = 5;
declares and initializes an object with type const int whose value will not be changed by a correct program. (The order of the keywords is not significant to C. For example, the declarations:
   int const five = 5;
   const five = 5;
are identical to the above declaration in its effect.)

The declaration:

   const int *pci = &five ;
declares an object with type pointer to const int, which initially points to the previously declared object. Note that the pointer itself does not have a qualified type -- it points to a qualified type, and as such, the pointer can be changed to point to essentially any int during the program's execution, but pci cannot be used to modify the object to which it points unless a cast is used, as in the following:
   *(int *)pci = 17;
(If pci actually points to a const object, the behavior of this code is undefined.)

The declaration:

   extern int *const cpi;
says that somewhere in the program there exists a definition of a global object with type const pointer to int. In this case, cpi's value will not be changed by a correct program, but it can be used to modify the object to which it points. Notice that const comes after the * in the above declaration. The following pair of declarations produces the same effect:
   typedef int *INT_PTR;
   extern const INT_PTR cpi;
These can be combined as in the following declaration in which an object is declared to have type const pointer to const int:
   const int *const cpci;

Next topic: Using const to read character values
Previous topic: Types for lvalues

© 2003 Caldera International, Inc. All rights reserved.
SCO OpenServer Release 5.0.7 -- 11 February 2003