您的位置:首页 > 其它

const和指针结合使用的例子

2014-06-09 15:19 253 查看
刚开始看《Effective C++》这本书,里面讲到const。我按照书上讲的,简单的写了个例子。如下。备忘。

#include <stdio.h>
int main()
{
	/*
	//下面const的用法表示const修饰的是p所指向的值是常量
	int i = 10;
	int k = 20;
	const int *p = &i;
	printf("%x\n",p);
	//*p = 20; //这一句是错误的,*p所指向的值是常量
	p = &k;
	printf("%x\n",p);
	printf("%d",*p);
	*/

	//下面演示const修饰指针本身的情况
	int m = 100;
	int n = 200;
	char * const p = (char * const)&m; //如果不加(char * const)会提示错误
	printf("%x\n",p);
	printf("%d\n",*p);
	
	//p = (char * const)&n;  //提示错误,不能给常量p赋值
	*p = 50;
	printf("%x\n",p);
	printf("%d\n",*p);
	getchar();
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: