Section 2: Compiler
67
TI
-
89 / TI
-
92 Plus Sierra C Assembler Reference Manual
Not for Distribution
Beta Version February 2, 2001
2.9.8. Const Type Specifier
The value of an object that is declared with the
const
type specifier cannot be
modified; therefore, the object cannot appear as the left-hand side of an
assignment, nor as the operand of the '++' or '
−
−
' operator. The following
examples demonstrate the legality of various modifications involving
const
objects:
const int a = 99;
const int b = 66;
const int *p = &a;
a++; /* illegal */
b
−−
; /* illegal */
a = 10; /* illegal */
p = &b; /* legal */
*p = 20; /* illegal */
The
const
type specifier can be used with integer types, floating-point types,
structure and union types, and enumeration types. It can also be used with
individual members of structures and unions, in which case only the specified
members are affected. If the
const
type specifier is used without any other type
specifiers or with only the
volatile
type specifier (see below), type
int
is implied.
The
const
type specifier can also be used to declare pointers to constant objects
and constant pointers to constant and nonconstant objects. Just as an asterisk
(
*
) in a declaration indicates a pointer to an object, the construct *
const
indicates a constant pointer to an object. A constant pointer cannot be modified;
no restrictions are placed on the object to which it points. The following
declarations define a constant
int
, a constant pointer to an
int
, and a constant
pointer to a pointer to a constant pointer to a constant
double
, respectively:
const int a;
int
*
const b;
const double
*
const
**
const c;
A pointer to a nonconstant object can be assigned to a pointer to either a
constant or nonconstant object; however, a pointer to a constant object can only
be assigned to a pointer to a constant object. These pointer assignment rules
were established to help prevent accidental modifications of constant objects with
dereferenced pointers to nonconstant objects. These rules can be easily
sidestepped with a type cast, but this is not recommended since it could result in
an attempt to modify data stored in Read-Only Memory (ROM).