c++ - 为什么必须在 C 中向后读取指针声明?

标签 c++ c pointers syntax

<分区>

在C语言中,对于简单的情况,似乎为了读取指针声明你必须向后进行。例如:

int n; 
int *p = &n; // p is a pointer to int
int *const np = &n; // np is a const pointer to int
int *const *npp = &np; //npp is a (non-const) pointer to const pointer to (non-const) int

尽管解析类型声明的正确方法是通过所谓的 the spiral rule , 如果解析规则不同以便以另一种方式适应简单指针声明的读取,那不是更容易吗? 例如:

int n;
*int p = &n; // p is a pointer to int
const *int np = &n; // np is a const pointer to int
*const *int npp = &np; // npp is a (non-const) pointer to const pointer to (non-const) int

那么我的问题又来了:这样的设计选择背后的原则是什么?是什么促使语言设计者选择这种特殊的方式来声明类型。

最佳答案

抛开语法。如果我没有弄错背后的想法:

int **a;

如下。您需要取消引用 a 两次才能获得 int。这样 const 位置也开始有意义。

int * const * a;

这实际上意味着您需要取消引用一次以获得指向 int 的 const 指针。


您可能会发现阅读有关 C 起源的文章既有趣又有教育意义。 (PDP、B等)

关于c++ - 为什么必须在 C 中向后读取指针声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44783184/

相关文章:

c++ - 使用 C++ 基类构造函数?

c - ATmega16 编程器寄存器不匹配

c++ - 调用 C++ 函数并更改其参数(链表)

pointers - 修改原始值时更改借用值

c++ - 函数计算对数

c++ - 编译OpenBLAS C++项目给出错误 “Undefined symbols for architecture x86_64”

c++ - pthread_cond_wait() 能否始终赢得锁定互斥体的竞争?

C计算字符串长度

objective-c - 指针在 Objective-C 中是如何工作的

c++ - 我可以将 char*(月份)与字符串(二月)进行比较吗?如果没有,我该怎么做呢?