(Created page with "'''const''' is a C keyword and a type qualifier that declares an object to be nonmodifiable. The const ...") |
(No difference)
|
Revision as of 06:04, 6 January 2014
const is a C keyword and a type qualifier that declares an object to be nonmodifiable. The const keyword can only appear once in a declaration. Objects declared with const
in their declaration must not be assigned to a value during the execution of a program.
The main purpose of const-qualified objects is to allow compilers to place such values in read-only memory. Additionally const-qualified objects might allow compilers to perform some additional consistency checks and possibly warn about invalid uses.
Pointers
Pointers can be both const-qualified and point to objects that are const-qualified.
pointer to a const value
It is possible and legal to take the address of an object which is declared using the const
qualifier as long as the pointer points to a const type. For example,
const int i = 1000;
const int *iptr = &i;
It is also allowed and safe to assign an address of an object which is not const
-qualified. Doing so will allow the code to inspect the value the pointer points to but not modify that value. For example,
int i = 1000;
const int *iptr = &i; /* the value iptr points to can be inspected but not modified using this pointer */
const pointer
It is possible to create a const
pointer. Doing so creates a pointer object that can not be modified, however the value it points to can be modified. For example,
int i = 1000;
int *const iptr = &i;
The pointer iptr
cannot be assigned to any other address, however the value it points to can be modified.