为什么指针声明中的星号特定于标识符而不是数据类型?
愚蠢的问题,但试图掌握潜在的机制/哲学来巩固我的理解。
int myInt; // declares a variable of type integer, named myInt. Intuitive. int* myPtr; // declares a variable of type pointer-to-integer. Also intuitive. int myInt2, myInt3; // two more integer variables.. yay!! This makes sense. // so the pattern is [type] [identifier] ; int* myInt4, myInt5; // an int pointer then an integer. Brain hurts!
TL; DR – 这是C语法设计的工作方式。
*
被认为是附加到变量,因为它定义了变量的类型 ,而不是数据类型 。 对象的类型应该是对象本身的属性,因此考虑属性的标识符与对象(变量)相关联是有意义的。
通过说int * p;
来澄清int * p;
,我们的意思是说, p
是指向 int
的类型指针的变量。 因此,将*
附加到变量而不是数据类型是有意义的。
你期待什么样的答案? 这就是C的工作原理。 如果你不喜欢它,Bjarne Stroustrup(C ++的创建者)同意你的意见,并建议你不要做你在最后一行做的事情。
它对C的制作者来说是有意义的,而且,它的共同点是将*
放在变量旁边而不是旁边的类型,这样就不那么容易混淆了:
int *myInt4, myInt5; // an int pointer then an integer.
如果使用clang-format
格式化源代码,这是样式选项PointerAlignment
,您需要的选项是PAS_Right
。
int* myInt4, myInt5
; //一个int指针然后是一个整数。 大脑疼!
这只是样式,编译器会正确解释它。 从理论上讲,你可以把*任何地方。
Type* variable; Type * variable; Type *variable;
它可以理解为:
int* myInt4, myInt5
;`//指针变量(myInt4)和int类型的变量(myInt5)。