为什么指针声明中的星号特定于标识符而不是数据类型?

时间:2016-01-13 04:11:37

标签: c pointers types syntax

愚蠢的问题,但试图掌握潜在的机制/哲学以巩固我的理解。

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] <,more-identifiers>;

int* myInt4, myInt5; // an int pointer then an integer. Brain hurts!

3 个答案:

答案 0 :(得分:4)

TL; DR - 这就是C语法的工作方式。

int * p;被视为附加到变量,因为它定义变量的类型,而不是数据类型 。对象的类型应该是对象本身的属性,因此考虑属性的标识符与对象(变量)相关联是有意义的。

通过说p来澄清,我们的意思是说,int指针类型的变量,它指向*。因此,将function (req, res, next) {} 附加到变量而不是数据类型是有意义的。

答案 1 :(得分:2)

您期待什么样的答案?这就是C的工作原理。如果你不喜欢它,Bjarne Stroustrup(C ++的创建者)同意你的意见,并建议避免做你在最后一行做的事情。

这对C的制作者来说是有意义的,而且,将*放在变量的旁边而不是在类型的旁边,以便减少混淆:

int *myInt4, myInt5; // an int pointer then an integer.

如果您使用clang-format格式化源代码,则这是样式选项PointerAlignment,您想要的选项为PAS_Right

答案 2 :(得分:0)

int* myInt4, myInt5; //一个int指针然后是一个整数。大脑疼!“

这只是样式,编译器会正确解释它。 从理论上讲,你可以把*任何地方。

 Type* variable;
 Type * variable;
 Type *variable;

可以理解为:

int* myInt4, myInt5;`//指针变量(myInt4)和类型为int的变量(myInt5)。