指向常量的指针可以用以下两种方式编写:
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/