const修饰基本数据类型(int、double、float、char)
被const修饰的变量为只读变量,不能修改,但可以在初始化时赋值。
#include <iostream>
using namespace std;
int main(){
const int i = 10;
i = 20; //不能修改被const修饰的变量的值
return 0;
}
const修饰数组
被const修饰的数组为只读数组,数组中每个元素都不能修改
#include <iostream>
using namespace std;
int main(){
const int arr[5] = {1,2,3,4,5};
arr[2] = 13; //不能修改
return 0;
}
const修饰指针变量
这里要区分指针变量本身和指针指向的值,分为两种情况,会有不同影响。
const int* p;//p指向的是一个常量
int const * p;//p指向的是一个常量
int* const p;//p是一个常量指针
总之,const可以放在三个位置,其中任何在*左侧的const代表的都是数据为常量,任何在*右侧的const都使得指针为常量
const在函数传参中的作用
有时不可避免的,我们会在函数传入参数中使用指针,但是并不期望函数内部能够通过指针修改数据,这时就需要用到const关键字,将传入参数(指针)声明为指向的是常量即可,如下:
void display(const int* arr,int length);//在函数内部不可以通过arr指针修改数组元素
const在函数返回值中的作用
有时函数会返回一个指针变量,指针所指向的数据块中有我们想要的数据,但是我们又不想函数外的代码对数据进行更改,就需要用到const来修饰返回值。
#include <iostream>
using namespace std;
const Person* generatePerson();//函数声明
int main(){
const Person* p=generatePerson();//函数调用
//此处必须用const声明变量p,因为不可以将const Person*类型数据转变为Person*
}