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等)
为什么你必须在C中向后读取指针声明?
在我看来,很难说声明是否真的倒退了.
我注意到在过去的几年里,我读到头脑中代码的方式发生了变化.
请考虑以下代码:
int *p;
Run Code Online (Sandbox Code Playgroud)
你怎么在头脑中读到这段代码?
我曾经读过: "p是指向int的指针".
现在我读到: "一个名为p的int指针".
经常使用这种语言,我的大脑已经改变了我将源代码翻译成英语的方式.这使我能够理解语法而不会感觉它倒退.
对我来说,感觉前进,虽然这完全是主观的,并且会因人而异.
此外,可能有许多(口头)语言,其中源代码很好地翻译成口语句子而不必改变排序.
宣言是否倒退取决于......