const限定符与指针

const限定符与指针

const 作用

如果一个变量使用const修饰,则表明该变量只能被访问,而不能被修改(const == “readonly”)。

#include "stdio.h"

int main(void)
{
	const int a = 0;
	int b = 0;

	a = 1;
		
	return 0;
}

编译报错

error: assignment of read-only variable ‘a’
  a = 1;

和指针结合情况一

const int * a;
int const * a;

这两个都是表达 a 是指向const int 型的指针,a所指向的内存单元的内容不能改变,但指针 a 可以改变,代码如下

	const int * a = NULL;  //int const * a;
	int b = 1;;
	
	a = &b;
	printf("const point test a = &b %d\n",*a);	
	*a = 100;
	printf("const point test a = 100 %d\n",*a);	
	return 0;

编译信息如下:

error: assignment of read-only location ‘*a’
*a = 100;

和指针结合情况二

int * const a;
a 是指向int 型的const指针,*a可以改变,a不允许改变

#include "stdio.h"

int main(void)
{
	int * const a = NULL; 
	int b = 1;
	
	*a = 100;
	printf("const point test a = 100 %d\n",*a);
	a = &b;
	printf("const point test a = &b %d\n",*a);	
		
	return 0;
}

编译报错

error: assignment of read-only variable ‘a’
a = &b;

和指针结合情况三

int const * const a;
这种情况下 a 和 *a都不能改写

const int * const a = NULL; 
	int b = 1;
	
	a = &b;
	printf("const point test a = &b %d\n",*a);	
	*a = 100;
	printf("const point test *a = 100 %d\n",*a);	
	return 0;	
		
	return 0;

编译结果

error: assignment of read-only variable ‘a’
 a = &b;
error: assignment of read-only location ‘*a’

*a = 100;

总结提升

明确const所修辞的对象,尽量使用const,提高代码的容错性。下面写法表示什么意思呢?
const char **p;
char *const *p;
char **const p;

猜你喜欢

转载自blog.csdn.net/HC_huangcheng/article/details/103820301