1. 程式人生 > >Pointer to constant vs Constant pointer

Pointer to constant vs Constant pointer

Pointer to constant

特點

對指標進行間接訪問後的內容是常量,不可更改
指標本身指向的地址不是常量,可更改

example

const int *ptr;
宣告ptr是指向const int型別的指標

const int var1 = 1,var2 = 2;  
const int *ptr = &var1;    
ptr = &var2;//right
*ptr = 0;//wrong

char *ptr= “Hi,World!”;

char *a = "hello";
char *b = "world";
a =b;//right
*a = "!!!!";//wrong

Constant pointer

特點

指標本身指向的地址是常量,不可更改
對指標進行間接訪問後的內容不是常量,可更改

典型宣告

int *const ptr
宣告ptr是指向int型別的const指標

example

int var1 = 1,var2 = 2; 
int *const ptr = &var1;    
*ptr = 0;//right
ptr = &var2;//wrong

wikipedia的經典案例

int *ptr; // *ptr is an int value
int const *ptrToConst; // *ptrToConst is a constant (int: integer value)
int * const constPtr; // constPtr is a constant (int *: integer pointer)
int const * const constPtrToConst; // constPtrToConst is a constant (pointer)
                                   // as is *constPtrToConst (value)
								   
void Foo( int * ptr,
          int const * ptrToConst,
          int * const constPtr,
          int const * const constPtrToConst )
{
    *ptr = 0; // OK: modifies the "pointee" data
    ptr  = NULL; // OK: modifies the pointer

    *ptrToConst = 0; // Error! Cannot modify the "pointee" data
    ptrToConst  = NULL; // OK: modifies the pointer

    *constPtr = 0; // OK: modifies the "pointee" data
    constPtr  = NULL; // Error! Cannot modify the pointer

    *constPtrToConst = 0; // Error! Cannot modify the "pointee" data
    constPtrToConst  = NULL; // Error! Cannot modify the pointer
}