Const, volatile and Pointers
It is possible to create a const pointer, a pointer to a const variable, a volatile pointer and a pointer to a volative variable.const int x = 5;
int const *ptrX = &x;
Here ptrX is a pointer to a const, not a const that also happens to ba a pointer. The const keyword modifies the item that is to the immediate right, which is the *, not ptrX. If the code had been as follows:int y = 10;
int *const ptrY = &y;
The const keyword in the above code would have modified ptrY, not the * and a const pinter to an integer would have been created. The pointer is constant, not the item being pointed to. If a pointer points at a const variable then the variable cannot be modified through that pointer. The pointer, which is not a const, can be modified.The pointer can be changed to point at a variable that is not const. If a pointer is defined as being a const pointer, then the pointer can never be modified but the memory to which it refers can be changed. In the above paragraphs, the keyword volatile can be substituted for wherever the word const is used. The syntax rules for using volatile are the same as those for const. The following program demostrates both correct and incorrect uses of const.
#include <iostream.h> int const X = 1; // X is a const const int Y = 2; const int *ptrY = &Y; // ptrY is a pointer to a const int const int Z = 3; int const *ptrZ = &Z; // ptrZ is also a pointer to const int int W= 4; int *const ptrW = &W; // const pointer to int int T = 5; // an integer const int *const ptrT; // uninitialized const pointer to const // int int main() { X = 10; // ERROR - cannot modify a const *ptrY = 11; // ERROR - cannot modify a const through a // pointer ptrY = &Z; // OKAY - ptrY itself is not const *ptrZ = 12; // ERROR - cannot modify a const through // a pointer ptrZ = &W; // OKAY - ptrZ itself is not const *ptrW = 13; // OKAY - ptrW does not point to a const ptrW = &T; // ERROR - cannot modify ptrW, it is a const ptrT = &T; // ERROR - cannot modify ptrT, it is a const return 0; }
No comments:
Post a Comment