c - 为什么有两种写常量指针的方法,但只有一种写常量指针的方法?

标签 c constants declaration qualifiers

指向常量的指针可以用以下两种方式编写:

int a = 5;

const int* b = &a;
/* or */
int const* c = &a;

但是常量指针只能这样写:

int a = 5;

int* const b = &a;

// const* int c = &a; This will not compile.

第二行将产生此错误:

expected identifier or '(' before 'int'

为什么不允许这样做?

最佳答案

在 C 声明中定义如下

declaration:
    declaration-specifiers init-declarator-list

例如在此声明中

const int* b = &a;

const int 是类型说明符,( *b ) = &a 是 init-declarator-list。

您可以重写上面的声明,例如

const int ( *b ) = &a;

如果你想让声明器成为一个常量对象,你应该这样写

const int ( * const b ) = &a;

您不能使用类型说明符(使用限定符除外)来分隔声明符,例如

const* int c = &a;

在此记录中,类型说明符 int 分割了声明符 *c

另一方面,您可以通过以下方式引入类型说明符

typedef const int *Ptr;

这种情况下可以将声明符写成常量

const Ptr b = &a;

在这种情况下,您将得到与

相同的声明
const int * const b = &a;

关于c - 为什么有两种写常量指针的方法,但只有一种写常量指针的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68168640/

相关文章:

c - 将 'const int' 分配给 'int' 时没有警告

c++ - 什么是 C++ 临时对象?

c++ - 我如何检查该函数是否真的获得了一个定义为 const 的变量?

java - 如何将列表中的get(0)转换为常量并获取值

c - C 中结构体数组的数组 - 声明

c++ - 如何减轻文件中远离其所有者命名空间声明的类声明?

c - 如果我在循环内声明变量有关系吗?

c++ - 内存相关崩溃: 3 Dimensional Array in Cocos2d Game

c - 在 C 中暂停线程一秒钟

c - C中的枚举数组