是否*或&事情? [英] Does the position of the * or & matters?
问题描述
Possible Duplicates:
In C, why is the asterisk before the variable name, rather than after the type?
What's your preferred pointer declaration style, and why?
在C ++中,我看到指针以不同的方式放置。例如
In C++, i see pointers put in different ways. for example,
char* ptr
char * ptr
char *ptr
上面的3个例子是否相同? (和&)一样。
Are the 3 examples above identical? (same goes with the &)
推荐答案
(例如它们是相同的)你甚至可以写入 char * ptr;
没有任何空格。
虽然在一行上有多个声明: char * ptr,noptr;
。这里,第三种语法更清楚: char * ptr,noptr;
。
我的规则避免混淆:每行只有一个变量。另一种方法做到这一点,没有可能错过 *
: typedef
指针,例如:
Doesn't matter. (Eg. they are the same.) You could even write char*ptr;
without any whitespace.
Beware though with multiple declarations on one line: char* ptr, noptr;
. Here, the third syntax comes in clearer: char *ptr, noptr;
.
My rule to avoid that confusion: Only one variable per line. Another way to do it right without the possibility to miss a *
: typedef
the pointer, eg:
typedef char* CharPtr;
CharPtr ptr1, ptr2; // now both are pointer
然而,你需要注意其他事情,例如 const
ness,所以我坚持我上面提到的规则:
Though then you need to be aware of other things, like const
ness, so I stick to my rule mentioned above:
typedef char* CharPtr;
const CharPtr p1; // const char* ?? or char* const ??
CharPtr const p2; // char* const ?? or const char* ??
// Eg.: Can't the pointer or the pointee be changed?
(以上所有内容也适用于&
)。
(And all of the above also applies to references &
.)
这篇关于是否*或&事情?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!