[user:lib_hdmanage] cat example/main.cpp
/// @file main.cpp
/// @brief
/// @author Easton Woo
/// 0.01
/// @date 2013-05-23
#include <stdio.h>
int main(int argc, char * argv[])
{
char *p = NULL;
char a[5] = {1,2,3,4,5};
const char* p1 = a; //指向常量的指针,(指向的内容不可变)
// *p1 = 10; //error: assignment of read-only location ‘* p1’;编译错误,不能通过该指针改变其指向的值
// *(p1+1) = 20; //error: assignment of read-only location ‘*(p1 + 1u)’;编译错误,不能通过该指针改变其指向的值
p1 = p; //正确,可以改变自己
p1++;
printf("%d\n",*p1);
printf("%d,%d,%d,%d,%d\n",a[0],a[1],a[2],a[3],a[4]);
char* const p2 = a; //指针常量,(自已的地址不可变)
*p2 = 10; //正确,可以改变值
*(p2+1) = 20; //正确,可以改变值
// p2 = p; //error: assignment of read-only variable ‘p2’;编译错误,不能改变自己
// p2++; //error: increment of read-only variable ‘p2’;编译错误,不能改变自己
printf("%d\n",*p2);
printf("%d,%d,%d,%d,%d\n",a[0],a[1],a[2],a[3],a[4]);
const char* const p3 = a; //指向常量的指针常量
// *p3 = 10; //error: assignment of read-only location ‘*(const char*)p3’;编译错误,不能改变值
// *(p3+1) = 20; //error: assignment of read-only location ‘*(((const char*)p3) + 1u)’;编译错误,不能改变值
// p3 = p; //error: assignment of read-only variable ‘p3’;编译错误,不能改变自己
// p3++; //error: increment of read-only variable ‘p3’;编译错误,不能改变自己
printf("%d\n",*p3);
printf("%d,%d,%d,%d,%d\n",a[0],a[1],a[2],a[3],a[4]);
return -1;
}
/*
const char*, char const*, char*const的区别问题几乎是C++面试中每次都会有的题目。
事实上这个概念谁都有只是三种声明方式非常相似很容易记混。
Bjarne在他的The C++ Programming Language里面给出过一个助记的方法:
把一个声明从右向左读。
char * const cp; ( * 读成 pointer to )
cp is a const pointer to char //也就是指针常量
const char * p;
p is a pointer to const char; //也就是指向常量的指针.
char const * p;
同上因为C++里面没有const*的运算符,所以const只能属于前面的类型。
*/