C中const修饰指针变量的不同情况

缘起

昨天看到指针,const 修饰这个部分给我看晕了,今天起来专门写个文章记忆一下

分类

修饰 p 指向内容(修饰*p)

1
2
const int* p = &a;
int const * p = &a;

两种写法等效,因为 const 都在*p左边

这种情况下,pconst int*型,const 修饰的是p指向的内容解引用后无法进行赋值操作

因为p本身没有被 const 修饰,所以指针的值可变,不必初始化

1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>
int main(void)
{
int a = 4;
int const *p;
p = &a;
a += 1; // 不用指针依然可以修改,因为a本身并未被const修饰
//*p += 1; // error: assignment of read-only location '*p'////
printf("%d %d", a, *p);
}
// 5 5

修饰 p

1
int* const p = &a;`

p 是int* const型,此时 const 修饰p必须在定义p时初始化

不初始化的话,p 就是一个野指针

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>
int main(void)
{
int a = 4;
int *const p = &a;
*p += 1 ; // 可行,因为*p并未被const修饰
//p += 1; // error: assignment of read-only variable 'p'
printf("%d %d",a,*p);
}
// 5 5

同时修饰 p 和 p 指向内容

其实就是上面两个方法的结合

1
2
const int* const p = &a;
int const * const p = &a;

两种写法等效

pp所指向内容都被 const 修饰,所以两者都不可改变

同样的,因为指针本身被修饰,必须定义时初始化

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>
int main(void)
{
int a = 4;
const int* const p = &a;
//*p += 1 ; // error: assignment of read-only variable 'p'
//p += 1; // error: assignment of read-only variable 'p'
printf("%d %d",a,*p);
}
// 4 4

总结

const修饰的,不能被修改

const 在*的左边,修饰的就是*p,也就是修饰p指向内容

const 在*的右边,修饰的就是p,也就是p本身

参考

C/C++ const 修饰指针变量的三种情况

Author

BakaFT

Posted on

2020-07-25

Updated on

2023-12-28

Licensed under

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×