Pointers and Constants
以下內容摘自The C++ Programming Language
void f1(char *p){
char s[] = "Gorm";
const char *pc = s;
pc[3] = 'g'; // error: pc points to constant
pc = p; // ok
char *const cp = s;
cp[3] = 'a'; // ok
cp = p; // error: cp is constant
const char *const cpc = s;
cpc[3] = 'a'; // error: cpc points to constant
cpc = p; // error: cpc is constant
}
char *const cp; //const pointer to char
char const* pc; //pointer to const char
const char* pc2; //pointer to const char
to read each such declarations right-to-left. ex: "cp is a const pointer
to a char" and "pc2 is a pointer to a char const".
void f4(){
int a = 1;
const int c = 2;
const int *pl = &c; // ok
const int *p2 = &a; // ok
int *p3 = &c; // error: initialization of int* with const int*
*p3 = 7;
}
沒有留言:
張貼留言