c++ - 为什么 c++ 指针 * 关联到声明的变量,而不是类型?

标签 c++ pointers language-design declaration

为什么 C++ 被设计成在同一行声明两个 int *s 的正确方法是

int *x, *y;

不是

int* x,y;

我知道有些人认为您应该避免使用任何一种形式并在单独的行中声明每个变量,但我对为什么做出这种语言决定很感兴趣。

最佳答案

为了保持与 C 代码的兼容性,因为 C 就是这样工作的。

Bjarne 提出了一个很好的观点 in his style and technique faq :

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.

因此,在 C++ 中像 this 这样工作的动机是它在 C 中的工作方式。

它在 C 中工作的动机是,如上所述,C 强调表达式而不是类型。

关于c++ - 为什么 c++ 指针 * 关联到声明的变量,而不是类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11032802/

相关文章:

c++ - 简单的项目不会编译

c++ - 如何使用 boost asio 通过 UDP 套接字发送 std::vector of unsigned char?

c++ - 是否可以使用 malloc 来增加现有数组的大小?

c - 在哪里以及如何正确释放 malloc 指针?

scala - 为什么在括号上使用花括号?

c++ - 链接错误 : undefined reference within the same class

C++指针参数问题

C++ 类和 Xcode

python - 编码语言定制

Javascript 明显的疯狂