【问题标题】:Why is the asterisk in a pointer declaration specific to the identifier and not the data type?为什么指针声明中的星号特定于标识符而不是数据类型?
【发布时间】:2016-01-13 04:11:37
【问题描述】:

愚蠢的问题,但试图掌握基本的机制/哲学来巩固我的理解。

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!

【问题讨论】:

  • 你的大脑很痛,因为你坚持使用与语言不一致的风格。
  • 应该是int *myPtr;int *myInt4, myInt5;stackoverflow.com/a/398414/125507
  • 我应该注意到我已经用 C++ 编码了一段时间,最后偶然发现了这种语言的怪异之处。我总是将星号左对齐,因为我认为指针是类型的一部分。它!您可以将int* 传递到模板中,int* 可以是某事的类型。唯一不适用的地方,afaik,是在变量声明器中,其中指针是标识符的一部分!即使这样,如果您只声明一个变量,它也是不可见的。我知道这是因为 C 是这样工作的,但我认为有些伤脑筋是有道理的。

标签: c pointers types syntax


【解决方案1】:

TL;DR - 这就是 C 语法的设计方式。

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

为了澄清,通过说int * p;,我们的意思是说,p 是一个指向int指针 类型的变量。因此,将* 附加到变量而不是数据类型是有意义的。

【讨论】:

    【解决方案2】:

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

    这对 C 的制造者来说是有意义的,而且,将 * 放在变量旁边而不是类型旁边是很常见的,这样就不那么混乱了:

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

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

    【讨论】:

      【解决方案3】:

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

      这只是样式,编译器会正确解释它。 理论上,您可以将 * 放在任何位置。

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

      可以读作:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多