c++ - C++ 中的 int *x 和 int* x 有区别吗?

标签 c++ variables pointers naming-conventions declaration

我正在重新开始我的 C++ 研究,并真正尝试了解基础知识。指针总是给我带来麻烦,我想确保我真的明白了,然后再继续下去并在路上感到困惑。

遗憾的是,我从一开始就被我正在阅读的教程中的不一致所困扰。有些人以这种方式进行指针声明:

int *x

有些人这样做:

int* x

现在两者中的前者似乎是迄今为止最常见的。这令人不安,因为第二个对我来说更有意义。当我读到 int *x 时,我读到“这是一个 int,它的名字是 *x”,这不太对。但是当我阅读第二个时,我看到“这是一个int指针,它的名字是x”,这很准确。

那么,在我建立自己的思维导图之前,两者之间是否存在功能差异?如果我这样做,我会成为麻风病人的弃儿吗?

谢谢。

最佳答案

著名的Bjarne Stroustrup ,以 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.

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.

所以,没有区别。这只是一种代码风格。

来自 here

关于c++ - C++ 中的 int *x 和 int* x 有区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15932925/

相关文章:

c++ - 我如何将其读入 Entry fname?

c++ - 将 void * 指向 char 作为 int 读取有多安全?

c++ - C++ 中的单向链表

c++ - 如何计算结构 vector (这是一个类成员,使用提取运算符)

c++ - 赋值运算符重载和自赋值

由 2 个文件共享的 C++ 变量

javascript - 带方括号的 Node.js 全局变量和函数 - 为什么这有效?

sql - mysql 变量赋值

C代码获取函数内的指针变量名称

在 C 中创建数组并将指向所述数组的指针传递给函数