C++ const用法

搜索C++ const的用法,到处都是

// (int*) const para25 = (int*)0x30000000;  // syntax error
// const (int*) para26 = (int*)0x30000000;  // syntax error
// const (int) * para27 = (int*)0x30000000;  // syntax error
// (int) const * para28 = (int*)0x30000000;  // syntax error

这样的例子,可惜弄下来编译都报语法错误,一群鸟人自己不验证到处乱转发,真是害人啊。。。


自己写了个验证的例子:

const int* para21 = (int*)0x30000000;
// *para21 = 2121;  // assignment of read-only location '* para21'
para21 = (int*)0x30000000;


// const* int para22 = (int*)0x30000000;  // syntax error


int const* para23 = (int*)0x30000000;
// *para23 = 2323;  // assignment of read-only location '* para23'
para23 = (int*)0x30000000;


int* const para24 = (int*)0x30000000;
*para24 = 2424;
// para24 = (int*)0x30000000;  // assignment of read-only variable 'para24'


从这个例子,可以看出:

1、const int* 和const* int二者的作用是一致的,指针变量的值可以改变,但是指针变量指向的内存单元中的值不能改变;

2、int* const则与前面二者的作用相反,指针变量的值不能改变,但是指针变量指向的内存单元中的值可以改变;


你可能感兴趣的:(C++ const用法)