现在的位置: 首页 > 综合 > 正文

const int *p 和 int* const p 的区别详解

2017年12月14日 ⁄ 综合 ⁄ 共 604字 ⁄ 字号 评论关闭

标准教科书答案如下:

const int * p : const右边接近于int这个类型声明,意思是有个指针p,指向的是一个int型的整数常量。即p可变,*p不可变。


下面程序说明*p不可变

int main()
{
	int a;
	const int* p = &a;//编译器将a看做const int型,所以该句不会出错
	//*p = 1;//l-value specifies const object,虽然声明的a 没有const标记,但由于p的效果,*p不能改变
	return 0;
}

下面程序说明p可变

int main()
{
	const int *p;
	int a,b;
	p = &a;
	p = &b;

	return 0;
}


int* const  p: const右边接近于*这个类型声明,意思是有个指向整数的常指针。即p不可变,*p可变。

下面程序说明p不可变

int main()
{
	int a,b;
	int* const p = &a;//const变量需要初始化
	//p = &b;//l-value specifies const object


	return 0;
}

下面程序说明*p可变

int main()
{
	int a;
	int* const p = &a;//const变量需要初始化
	*p = 1;


	return 0;
}

总的来说,抓住一点:const声明的变量不能出现在等号左边,

const int *p,中p指向的int为const,所以不能对*p赋值,即*p不可变。

int* const p,中p为const,不能对p赋值,所以p不可变

抱歉!评论已关闭.