C语言 int* p 和 int *p 声明之间的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5590150/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between int* p and int *p declaration
提问by karthik
Can you please tell me the difference between int* pand int *pdeclaration?
你能告诉我int* p和int *p声明之间的区别吗?
回答by user541686
There is no difference.
有没有什么区别。
It's a matter of notation, not semantics. The second is less misleading, because
这是一个符号问题,而不是语义问题。第二个较少误导,因为
int *a, b;
is clearly declaring an int*and an int, whereas
明确声明 anint*和 an int,而
int* a, b;
looks as if it's declaring two pointers, when it's really doing the same thing as above.
看起来好像在声明两个指针,实际上它确实在做与上面相同的事情。
回答by Tony Delroy
It's a good question.
这是个好问题。
int* p- widely used by C++ programmers
int* p, qwrongly implies that bothpandqare pointers (leading to a preference for declaring this on two lines, which also improves readability when there are assignments, and makes it easier to quickly cut/paste or comment specific lines/variables)int* pvisually separates the type from the identifier*pthen unambiguously indicates a dereference (assuming you put spaces around your binaryoperator*ala2 * 3)- in C++
...&xis clearly taking an address while...& xmust be declaring a reference variable, and... & ...is the bitwise-AND operator
int *p- widely used by C programmers
int *p, qclearly reflectspbeing a pointer andqnot being.int *pvisually confuses the type with the identifier- visually indistinguishable from a pointer dereference (for better or worse)
int* p- C++程序员广泛使用
int* p, q错误地暗示两者p和q都是指针(导致偏好在两行中声明,这也提高了赋值时的可读性,并使快速剪切/粘贴或注释特定行/变量变得更容易)int* p在视觉上将类型与标识符分开*p然后明确表示取消引用(假设您在二进制operator*ala周围放置了空格2 * 3)- 在 C++
...&x中显然需要一个地址而...& x必须声明一个引用变量,并且... & ...是按位与运算符
int *p- C程序员广泛使用
int *p, q清楚地反映了p是一个指针而q不是存在。int *p视觉上将类型与标识符混淆- 在视觉上与指针取消引用无法区分(无论好坏)
Similarly for types appearing in function declarations...
同样对于出现在函数声明中的类型......
int* f(), g(); // declares int g();
int *h(), (*i)(); // i is pointer to function returning int
int *const*m(), n(); // m returns pointer to (const-pointer to int)
// n returns int
...but at least function arguments can't get so hairy - the type specification starts afresh after each comma separators.
...但至少函数参数不能变得如此冗长 - 类型规范在每个逗号分隔符之后重新开始。
Summarily, int *pis better if your coding style / code-base utilises multiple declarations on a single line of source code, otherwise int* poffers a clearer separation of type and the following identifier.
总之,int *p如果您的编码风格/代码库在一行源代码上使用多个声明会更好,否则int* p提供更清晰的类型分离和以下标识符。
For all that, people's preferences are largely based on what they're used to.
尽管如此,人们的偏好很大程度上取决于他们的习惯。
回答by RonnieW
回答by CLH
those 2 declarations are exactly the same!
这两个声明完全一样!

