为什么你必须在C中读取指针声明后缀?

elF*_*eak 3 c c++ syntax pointers

在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
Run Code Online (Sandbox Code Playgroud)

即使解析类型声明的正确方法是通过所谓的螺旋规则,如果解析规则不同以便以另一种方式容纳简单指针声明的读取,这不是更容易吗?例如:

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
Run Code Online (Sandbox Code Playgroud)

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

小智 6

除了语法.如果我没有弄错背后的想法:

int **a;
Run Code Online (Sandbox Code Playgroud)

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

int * const * a;
Run Code Online (Sandbox Code Playgroud)

这个本质上意味着您需要取消引用一次以获取指向int的const指针.


您可能会发现有关C起源的有趣和有教育意义.(PDP,B等)

  • @EugeneSh.这是参考.作者:Dennis M. Ritchie本人:https://heim.ifi.uio.no/inf2270/programmer/historien-om-C.pdf在第7页,您会发现a)指针/数组/函数运算符确实早于C(来自它的无类型前辈),以及b)他确实定义了声明语法以匹配表达式语法. (2认同)

byx*_*xor 5

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

在我看来,很难说声明是否真的倒退了.

例如...

我注意到在过去的几年里,我读到头脑中代码的方式发生了变化.

请考虑以下代码:

int *p;
Run Code Online (Sandbox Code Playgroud)

你怎么在头脑中读到这段代码?

  • 我曾经读过: "p是指向int的指针".

  • 现在我读到: "一个名为p的int指针".

经常使用这种语言,我的大脑已经改变了我将源代码翻译成英语的方式.这使我能够理解语法而不会感觉它倒退.

对我来说,感觉前进,虽然这完全是主观的,并且会因人而异.

此外,可能有许多(口头)语言,其中源代码很好地翻译成口语句子而不必改变排序.

结论

宣言是否倒退取决于......

  • 你的母语.
  • 如何将代码翻译成您的母语.
  • 声明的大小/复杂性.