今天在复习<<C++ Primer Plus>> 章节7.3的时候想到以前做的一个题,const和指针运算符*的若干种组合的合法性和意义问题,有点混淆,所以写了一个测试代码来验证一下,简单明了,一目了然。如果有什么遗漏的话欢迎指出。
首先是在Ubuntu14.04.1下用gcc 4.8.4编译运行的结果,编译器报错信息都附加在对应语句后面的注释里
/*
* Note : Test for the combinations of const and *
* Last edit : 2016-2-27
*/
#include <iostream>
int main()
{
int a = 1, b = 2;
const int *p1 = &a;
p1 = &b;
// *p1 = 3; // error: assignment of read-only location ‘* p1’
int * const p2 = &a;
// p2 = &b; // assignment of read-only variable ‘p2’
*p2 = 3;
int const * p3 = &a;
p3 = &b;
// *p3 = 3; // error: assignment of read-only location ‘* p3’
// const * int p4 = &a; // error: expected unqualified-id before ‘int’
// int * p5 const = &a; // error: expected initializer before ‘const’
// const const int * p6