C++ 风格:Stroustrup 的指针星号放置

C++ style: Stroustrup' s placement of pointer asterisks

有谁知道为什么Stroustrup的风格是指针的放置如下?具体来说,Stroustrup 就此事提供了哪些指导?

int* p;

int *p;

因为声明多个变量需要在每个变量名称旁边加上星号。这将导致:

int* p, *x;

int *p, *x;

在 K&R C 书中,他们解释说 asterisk/pointer 用作助记符以帮助理解。我觉得奇怪的是 pointer/asterisk 与类型相关,而不是变量,如每个示例的第二个所示。有兴趣了解为什么选择第一种样式的背景。

希望在推理中引用 Stroustrup 的话。

我在 K&R C 第二版语法第 235 页中添加了星号(指针)与声明符相关联的位置,它是一个标识符。

回答 在此 article from Stroustrup 关于编码风格。他解释说两者都是有效的,这取决于程序员的偏好。

我不同意这是一个基于意见的问题。 Stroustrup 的文章清楚地回答了这个问题。

我相信 stroustrup 的风格意味着应该避免像这样的变量声明。这似乎也是社区的普遍共识。

我不能代表 Bjarne,但是将星号(和符号在引用的情况下)与类型联系起来是有道理的,因为指针在语义上是变量类型的一部分。变量的名称是 p,类型是 int*。名称不是 *p,类型也不是 int

几乎总是可以避免在单个声明中声明多个变量,因此这不是问题。

在我看来,这种方法更清晰,尤其是在 return 类型的情况下:

T*
function(Args...);

T
*function(Args...);

C++ 非常重视 类型 并且当谈到指针声明时,为了避免任何形式的混淆,Bjarne 建议 - Stick to one pointer per declaration.

来自 Bjarne Stroustrup's C++ Style and Technique FAQ [强调]:

Is int* p; right or is int *p; right?

Both are "right" in the sense that both are valid C and C++ and both have exactly the same meaning. As far as the language definitions and the compilers are concerned we could just as well say int*p; or int * p;

The choice between int* p; and int *p; is not about right and wrong, but about style and emphasis. C emphasized expressions; declarations were often considered little more than a necessary evil. C++, on the other hand, has a heavy emphasis on types.

A typical C programmer writes int *p; and explains it *p is what is the int emphasizing syntax, and may point to the C (and C++) declaration grammar to argue for the correctness of the style. Indeed, the * binds to the name p in the grammar.

A typical C++ programmer writes int* p; and explains it p is a pointer to an int emphasizing type. Indeed the type of p is int*. I clearly prefer that emphasis and see it as important for using the more advanced parts of C++ well.

The critical confusion comes (only) when people try to declare several pointers with a single declaration:

int* p, p1; // probable error: p1 is not an int*

Placing the * closer to the name does not make this kind of error significantly less likely.

int *p, p1; // probable error?

Declaring one name per declaration minimizes the problem - in particular when we initialize the variables. People are far less likely to write:

int* p = &i; int p1 = p; // error: int initialized by int*

And if they do, the compiler will complain.
Whenever something can be done in two ways, someone will be confused. Whenever something is a matter of taste, discussions can drag on forever. Stick to one pointer per declaration and always initialize variables and the source of confusion disappears.

See The Design and Evolution of C++ for a longer discussion of the C declaration syntax.