导航

Pointer and const

When using const with pointers, you have two options: const can be applied to what the pointer is pointing to, or the const can be applied to the address stored in the pointer itself.

Pointer to const
     The const specifier binds to the thing it is "closest to". 
     So if you want to prevent any changes to the element you are pointering to, you write a defination like this:
     const int *u; = int const *u;
     Here, no initialization is required because you're saying that u can point to anything( that is, it is not const), but the thing it
     points to cannot be changed.

Const pointer
    To make the pointer itself a const, you must place the const specifier to the right of the *, like this:
    int d = 1;
    int * const w= &d;
    Because the pointer itself is now the const, the compiler requires that it be given an initial value that will be unchanged for the
   life of that pointer. It's OK, howerver, to change what that value pointer to by saying:
    *w = 2;

Here are the above lines in a compileable file:
     const int *u;
     int const *v;
     int d = 1;
     int *const w = &d;
     const int *const x = &d;
     int const* const x2 = &d; 


You can assign the address of a non-const object to a const pointer because you're simply promising not to change something that is OK to change. However, you can't assign the address of a non-const pointer because then you're saying you might change the object via the pointer. 
    const int e = 2;
    int *w = (int *)&e; // Legal but bad practice.


//There is some error in the following  codes segment.

 char *szCharP = "hello";
 //*(szCharP + 1) = 't'; // build not error in VC6. but when running, it will be crashing.
 const char *t = szCharP;
// *(t + 2 ) = 10; // l-value is contanst, build error.
 szCharP = "world";
 cout << t <<endl; // hello
 cout << szCharP <<endl; //world

the compiler will allocate the storage about the contanst string ( like, "hello"), and assign the contanst string pointer to the variable parameter. 
 


posted on 2005-03-30 13:10  Raker  阅读(136)  评论(0)    收藏  举报