const int *,const int * const和int const *之间的区别

在这里插入图片描述

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.

  • 23
    点赞
  • 61
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值