修饰变量:
int const a;
cont int a;
这两者是等价的。代表不可以改变的常量。
const修饰的是a代表a不可作为左值。
修饰指针
1:常量指针
const int *b=& base;
或者
int const *c=& base;
2:指针常量
int * const d=&base1;
此时要求const 在*号前面。
3:指向常量的常指针
int const* const e=&base2;
const int * const f=&base2;
下面是代码:
#include <cstdio>
using namespace std;
int main()
{
const int constint=1;
int const constin2=2;
//常量指针
int base=1;
int *a=&base;
const int *b=&base;
int const *c=&base;
//常量指针指向的变量可以通过其他途径修改,
int*p=&base;
*p=2;
//但是不能通过这个指针来改变。
//*b=3;//这样是会报错的
//*c=3;//这样是会报错的
//但是可以这样
int change=3;
b=&change;
c=&change;
//但是对于指针本身而言,它依然可以指向别的单元。
//指针常量
int base1=1;
int * const d=&base1;
int change3=2;
//d=&change3; //这样是会报错的,因为指针本身是常量。
//指向常量的常指针
int base2=1;
int const* const e=&base2;
const int * const f=&base2;
int change4=3;
//*e=3;
//*f=3;//这两种情况都会报错,因为这是常指针,不能通过指针来修改指向变量的值
//e=&change4;
//f=&change4;//这两种情况都会报错,因为这是指针常量,指针时常量,不能修改其指向。
int *p3=&base2;
*p3=3;
//虽然不能通过,指向单元的常指针修改,也不能修改指针的指向,但是这都是指针的事情,和指向单元的关系不大
//所以还是可以通过其他途径修改指向单元的值。
printf("*a %d\n",*a);
printf("*b %d\n",*b);
printf("*c %d\n",*c);
printf("*d %d\n",*d);
printf("*e %d\n",*e);
printf("*f %d\n",*f);
return 0;
}
输出结果:
*a 2
*b 3
*c 3
*d 1
*e 3
*f 3
Process returned 0 (0x0) execution time : 0.120 s
Press any key to continue.