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

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

声明:本文翻译自:Difference between const int*, const int * const, and int const * - GeeksforGeeks

Pointer with Constans

int const* 和 const int*

int const* 是一个指向整型常量(const int)的指针(*)类型。这意味着变量将被声明为一个指向 const int 变量的指针。实际上,这表明了指针指向的是一个不能被修改的变量。在这个情况下,const 对指针并没有限定作用,指针可以指向任何合法的地址。第一个const 关键字可以位于数据类型的任意一侧,所以 int const*const int* 是等价的。

#include <stdio.h>
 
int main(){
    const int q = 5;
    int const* p = &q;
 
    // 编译错误
    *p = 7;
 
    const int q2 = 7;
 
    // 合法
    p = &q2;
     
    return 0;
}

译注:p 也可以指向非 constint 类型变量,只不过依然不能通过 *p 来修改 p 指向的非 constint 类型变量。因为 *p 被声明为 const 类型。

int* const

int* const 是一个指向整型变量(int)的指针常量(* const)类型。这意味着变量将被声明为一个指向 int 类型的 const 指针。 实际上,这表明了指针不能指向任意的地址(所以指针应当在定义时初始化)。但是这种情况下,constint 类型并没有任何影响,所以 int* const 类型的指针指向的内存地址中的值是可修改的。

#include <stdio.h>
 
int main(){
    int q = 5;
    int *const p = &q;
 
    // 合法
    *p = 7;
 
    const int q2 = 7;
 
    // 编译错误
    p = &q2;
 
    return 0;
}

const int* const

const int* const 是一个指向整型常量(const int)的指针常量(* const)类型。这意味着变量被声明为一个指向 cosnt int 类型的 const 指针。实际上,这表明了 const 指针指向的是一个常量。因此,指针指向的变量和指针本身都是不能修改的。和第一种情形类似,const int* constint const* const 是等价的,第一个 cosnt 关键字可以在数据类型声明的任意一边。

#include <stdio.h>
 
int main(){
    const int q = 5;
 
    // 合法
    const int* const p = &q;
 
    // 编译错误
    *p = 7;
     
    const int q2 = 7;
 
    // 编译错误
    p = &q2;
     
    return 0;
}

内存映射(Memory Map)

可以用 “螺旋法则” 来记住这个语法(根据于 Bjarne Stroustrup 博士 —— C++ 之父)。“螺旋法则” 是这样描述的:从变量名开始,顺时针移动到下一个指针(运算符)或者类型名。重复这个步骤直到表达式结束。

spiral rule

这个法则也可以理解为 ”从右到左解析语法“。

因此,

  • int const* 是指向 const int 的指针(pointer to const int)。
  • int* const 是指向 intconst 指针(const pointer to int)。
  • int const* const 是指向 const intconst 指针(const pointer to const int)。

甚至可以使用一个法则来解析复杂的声明,

  • int** const 是指向 int 的指针的 const 指针(const pointer to pointer to an int)。
  • int* cosnt * 是指向 intconst 指针的指针(pointer to const pointer to an int)。
  • int cosnt** 是指向 const int 的指针的指针(int const ** is a pointer to a pointer to a const int)。
  • int* const* const 是指向 intconst 指针的 const 指针( const pointer to a const pointer to an int)。
posted @ 2022-12-16 17:48  主修社科懂点技术  阅读(10)  评论(0)    收藏  举报