Type Qualifiers and Type Definitions
The
type of an object can be qualified by the
keywords const
and
volatile
in the declaration.
The type qualifier const indicates that the
program can no longer modify an object after its declaration. For
example:
const double pi = 3.1415927;
After this declaration, a statement that modifies the object
pi, such as pi = pi+1;, is
illegal and results in a compiler error.
The type qualifier volatile indicates
variables that can be modified by
processes other than the present program. Based on this information,
the compiler may refrain from optimizing access to the variable.
The type qualifiers volatile and
const can also be combined:
extern const volatile unsigned clock_ticks;
After this declaration, clock_ticks cannot be
modified by the program, but may be modified by another process, such
as a hardware clock interrupt handler.
Type qualifiers are generally prefixed to the type specifier. In pointer declarations, however, type qualifiers may be applied both to the pointer itself and to the object it addresses. If the type qualifier is to be applied to the pointer itself, it must be placed immediately before the identifier.
The most common example of such a declaration is the “pointer to a constant object.” Such a pointer may point to a variable, but cannot be used to modify it. For this reason, such pointers are also called “read-only” pointers. For example:
int var1 = 1, var2 = 2, *ptr; const int cArr[2]; const int *ptrToConst;// "Read-only pointer" ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access