在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
所以我的问题再次提出:这种设计选择背后的原理是什么?是什么促使语言设计者选择这种特殊方式来声明类型。
答案 0 :(得分:6)
int **a;
如下。您需要取消引用两次才能获得int。通过这种方式,const位置也开始变得有意义了。
int * const * a;
这个本质上意味着你需要取消引用一次以获得指向int的const指针。
您可能会发现阅读C起源有趣且有教育意义。 (PDP,B等)
答案 1 :(得分:5)
为什么必须在C中向后读取指针声明?
在我看来,很难说声明是否真正向后倾斜。
我注意到在过去的几年里,我读到头脑中代码的方式发生了变化。
请考虑以下代码:
int *p;
你如何在头脑中阅读这段代码?
我曾经读过:“p是指向int的指针”。
现在我读了:“一个名为p的int指针。”
经常使用这种语言,我的大脑改变了我将源代码翻译成英语的方式。这使我能够理解语法而不会感觉它倒退。
对我来说,它感觉前锋,虽然这完全是主观的,并且会因人而异。
此外,可能有许多(口头)语言,源代码可以很好地翻译成口语句子而无需更改排序。
声明是否倒退可能取决于......