const限定符与指针

本文详细解析了C/C++中const限定符与指针的结合使用,阐述了const修饰变量、指针及指针指向内容的不同情况,通过实例演示了编译错误及其原因,帮助读者理解并正确运用const提高代码质量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值