1 const修饰指针
const是 constant 的缩写,本意是不变的,不易改变的意思。在 C++ 中是用来修饰内置类型变量,自定义对象,成员函数,返回值,函数参数。C++
const允许指定一个语义约束,编译器会强制实施这个约束,允许程序员告诉编译器某值是保持不变的。如果在编程中确实有某个值保持不变,就应该明确使用const,这样可以获得编译器的帮助。
1.1 const修饰变量
变量是可以修改的,如果把变量的地址交给一个指针变量,通过指针变量也可以修改这个变量。但是如果我们希望一个变量加上一些限制,不能被修改,怎么做呢?这就是const的作用。
可见无法直接修改n的值了,编译器会报错。
不过,如果我们绕过n,使用n的地址,去修改n就能做到了,虽然这样做是在打破语法规则。
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main()
{
int const n = 10;
//n = 3;
int* p = &n;
*p = 5;
printf("%d", *p);
return 0;
}
n的值通过指针被修改了,但是我们还是要思考一下,为什么n要被const修饰呢?就是为了不能被修改,如果p拿到n的地址就能修改n,这样就打破了const的限制,这是不合理的,所以应该让p拿到n的地址也不能修改n,那接下来怎么做呢?
1.2 const修饰指针变量
一般来讲const修饰指针变量,可以放在*的左边,也可以放在*的右边,意义是不一样的。
int* const p;//放在*的右边
int const* p;//放在*的左边
我们来看看下面的对比代码:
void test1()
{
int n = 10;
int m = 20;
int* const p = &n;
p = &m;
*p = 50;
}
void test2()
{
int n = 10;
int m = 20;
int const* p = &n;
p = &m;
*p = 50;
}
int main()
{
//int* const p
test1();
//int const* p
test2();
return 0;
}
结论:const修饰指针变量的时候
const如果放在*的左边,修饰的是指针指向的内容,保证指针指向的内容不能通过指针来改变。但是指针变量本身的内容可变。(不能通过*p = ...来修改目标值)const如果放在*的右边,修饰的是指针变量本身,保证了指针变量的内容不能修改,但是指针指向的内容,可以通过指针改变。(不能p = ...来改变指针指向)
还有一种常见情况,*的左右两边都有const。这样指针本身和指向的内容都不可修改。
void test3()
{
int n = 10;
int m = 20;
int const* const p = &n;
p = &m;//报错
*p = 50;//报错
}
int main()
{
//int const* const p
test3();
return 0;
}