在 C/C++ 中声明指针变量的正确方法

2021-12-13 00:00:00 pointers c coding-style c++

我注意到有些人使用以下符号来声明指针变量.

I noticed some people use the following notation for declaring pointer variables.

(a) char* p;

代替

(b) char *p;

我使用 (b).符号(a)背后的理性是什么?符号 (b) 对我来说更有意义,因为字符指针本身不是一种类型.相反,类型是字符,变量可能是指向字符的指针.

I use (b). What is the rational behind the notation (a)? Notation (b) makes more sense to me because character pointer is not a type itself. Instead the type is character and the variable may be a pointer to the character.

char* c;

这看起来像是 char* 类型,而变量 c 就是这种类型.但实际上类型是char,而*c(c指向的内存位置)是那种类型(char).如果您一次声明多个变量,这种区别就很明显了.

This looks like there is a type char* and the variable c is of that type. But in fact the type is char and *c (the memory location pointed by c) is of that type (char). If you declare multiple variables at once this distinction becomes obvious.

char* c, *d;

这看起来很奇怪.c 和 d 都是指向一个字符的同一种指针.在这一点上,因为下一个看起来更自然.

This looks weird. Both c and d are same kind of pointers that point to a character. In this since the next one looks more natural.

char *c, *d;

推荐答案

Bjarne Stroustrup 说:

Bjarne Stroustrup said:

int* p;"之间的选择和int * p;"不在于对与错,而在于风格和重点.C 强调表达式;声明通常被认为只不过是一种必要的罪恶.另一方面,C++ 非常重视类型.

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.

典型的 C 程序员"写int *p;"并解释它*p 是什么是 int";强调语法,并可能指向 C(和 C++)声明语法来争论风格的正确性.实际上,* 绑定到语法中的名称 p.

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.

典型的 C++ 程序员"写int* p;"并解释它p 是一个指向 int 的指针";强调类型.实际上 p 的类型是 int*.我显然更喜欢这种强调,并且认为这对于很好地使用 C++ 的更高级部分很重要.

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.

来源:http://www.stroustrup.com/bs_faq2.html#whitespace

我推荐后一种风格,因为在您在一行中声明多个指针的情况下(您的第 4 个示例),使用带有星号的变量将是您所习惯的.

I'd recommend the latter style because in the situation where you are declaring multiple pointers in a single line (your 4th example), having the asterisk with the variable will be what you're used to.

相关文章