int const*
int const* 是指向常量整数的指针。
这意味着被声明的变量是指向常量整数的指针。实际上,这意味着指针指向了不应更改的值。在这种情况下,const限定符不会影响指针,因此允许指针指向其他地址。
第一个const关键字可以放在数据类型的任何一侧,因此int const *等价于同于const int *。
#include <stdio.h>
int main(){
const int q = 5;
int const* p = &q;
//Compilation error
*p = 7;
const int q2 = 7;
//Valid
p = &q2;
return 0;
}
int *const
int * const是指向整数的常量指针。
这意味着要声明的变量是指向整数的常量指针。实际上,这意味着指针不应指向其他地址。在这种情况下,const限定符不会影响整数的值,因此允许更改存储在地址中的值。
#include <stdio.h>
int main(){
const int q = 5;
//Compilation error
int *const p = &q;
//Valid
*p = 7;
const int q2 = 7;
//Compilation error
p = &q2;
return 0;
}
const int* const
const int * const是指向常量整数的常量指针。
这意味着要声明的变量是指向常量整数的常量指针。实际上,这意味着常量指针指向常量值。因此,指针既不应指向新地址,也不应更改所指向的值。
第一个const关键字可以位于数据类型的任一侧,因此const int*const等价于int const*const。
#include <stdio.h>
int main(){
const int q = 5;
//Valid
const int* const p = &q;
//Compilation error
*p = 7;
const int q2 = 7;
//Compilation error
p = &q2;
return 0;
}
记忆图
记住语法的一种方法是螺旋规则-
规则说,从变量名开始,顺时针移动到下一个指针或类型。重复,直到表达式结束。
该规则也可以看作是从右到左解码语法。
因此,
- int const* 是指向 const int 的指针
- int *const 是指向 int 的 const 指针
- int const* const 是指向 const int 的 const 指针
使用此规则,即使是复杂的声明也可以被解码,例如,
- int ** const 是指向int的指针的const指针。
#include <stdio.h>
int main()
{
int a = 5;
int * p1 = &a;
int ** const p2 = &p1;
printf("*p1 = %d\n", *p1);
printf("**p2 = %d\n", **p2);
}
- int * const * 是指向const指针的指针,其中const指针指向int。
- int const ** 是指向指针的指针,里面的指针指向 const int。
- int * const * const 是指向const指针的const指针,里面的const指针指向 int。
参考文档
[1]palaknarula.Difference between const int*, const int * const, and int const *[EB/OL].https://www.geeksforgeeks.org/difference-between-const-int-const-int-const-and-int-const/?ref=rp,2020-01-03.