八股——const 关键字

1.const作用

作用:const用于保护指针指向数据不被修改

测试代码1

显示数组的函数不小心修改了指针指向的值,这时候没有加const关键字,编译器不会报错

cpp 复制代码
#include <stdio.h> 

void  showar(int ar[]);

int main(void)
{
	int ar[4]={2,3,4,5};
	showar(ar);
//	muliar(ar);
	
	return 0;
	
} 

void  showar(int ar[]){
	int i;
	for(i=0;i<4;i++){
        ar[i]++;
		printf("ar[%d]:%d\n",i,ar[i]);
		
	}
	
}

测试代码2

显示数组的函数不小心修改了指针指向的值,这时候 加const关键字,编译器报错

cpp 复制代码
#include <stdio.h> 

void  showar(const int ar[]);

int main(void)
{
	int ar[4]={2,3,4,5};
	showar(ar);
//	muliar(ar);
	
	return 0;
	
} 

void  showar(const int ar[]){
	int i;
	for(i=0;i<4;i++){
		ar[i]++;
		printf("ar[%d]:%d\n",i,ar[i]);
		
	}
	
}

2.const与#define区别

const的限定有限,限定的是自己,限定的是常量,别人要修改也管不着。

3.const的3种用法

const int *p=ar;

这样限定的是指针p不能修改指向的值 *p 或 p[2],但是仍然可以修改p的指向或者ar

int * const p=ar;

这样限定的是指针p能修改 指向的值*p / p[2],但是不可以修改p的指向

const int * const p=ar;

这样限定的是指针p不能修改 指向的值*p / p[2],也不可以修改p的指向

相关推荐
小码哥_常10 小时前
Spring Boot:别再重复造轮子,这些内置功能香麻了
后端
皮皮林55111 小时前
OpenFeign 首次调用卡 3 秒?八年老开发扒透 5 个坑,实战优化到 100ms!
后端
千寻girling12 小时前
《 Git 详细教程 》
前端·后端·面试
0xDevNull13 小时前
Linux 中 Nginx 代理 Redis 的详细教程
redis·后端
GetcharZp14 小时前
告别 Nginx 手动配置!这款 Go 语言开发的云原生网关,才是容器化时代的真香神器!
后端
RuoyiOffice14 小时前
SpringBoot+Vue3 企业考勤如何处理法定假期?节假日方案、调休补班与工作日判断链路拆解
spring boot·后端·vue·anti-design-vue·ruoyioffice·假期·人力
Vane114 小时前
从零开发一个AI插件,经历了什么?
人工智能·后端
9523615 小时前
SpringBoot统一功能处理
java·spring boot·后端
rleS IONS15 小时前
SpringBoot中自定义Starter
java·spring boot·后端
DevilSeagull15 小时前
MySQL(2) 客户端工具和建库
开发语言·数据库·后端·mysql·服务