kee*_*eda 80 c c++ pointers coding-style
我注意到有些人使用以下表示法来声明指针变量.
(a) char* p;
Run Code Online (Sandbox Code Playgroud)
代替
(b) char *p;
Run Code Online (Sandbox Code Playgroud)
我用(b).符号(a)背后的理性是什么?符号(b)对我来说更有意义,因为字符指针本身不是一种类型.相反,类型是字符,变量可以是指向字符的指针.
char* c;
Run Code Online (Sandbox Code Playgroud)
这看起来像char*类型,变量c是该类型.但实际上类型是char和*c(c指向的内存位置)是该类型(char).如果一次声明多个变量,这种区别就变得很明显了.
char* c, *d;
Run Code Online (Sandbox Code Playgroud)
这看起来很奇怪.c和d都是指向字符的同一种指针.因为下一个看起来更自然.
char *c, *d;
Run Code Online (Sandbox Code Playgroud)
谢谢.
Bla*_*ack 94
Bjarne Stroustrup说:
"int*p;"之间的选择 和"int*p;" 不是对与错,而是关于风格和重点.C强调表达; 声明通常被认为只是一种必要的邪恶.另一方面,C++非常重视类型.
"典型的C程序员"写"int*p;" 并解释它"*p是什么是int"强调语法,并可能指向C(和C++)声明语法来争论样式的正确性.实际上,*绑定到语法中的名称p.
"典型的C++程序员"写"int*p;" 并解释它"p是指向int的指针"强调类型.实际上,p的类型是int*.我显然更喜欢这种强调,并认为它对于使用C++的更高级部分非常重要.
资料来源:http://www.stroustrup.com/bs_faq2.html#whitespace
我推荐后一种风格,因为在你在一行中声明多个指针的情况下(你的第四个例子),带有变量的星号将是你习惯的.
ike*_*ami 49
我个人更喜欢把它*
与其他类型
char* p; // p is a pointer to a char.
Run Code Online (Sandbox Code Playgroud)
人们会争辩"然后char* p, q;
变得误导",我说,"所以不要这样做".
Geo*_*aál 30
如何写是没有区别的.但是如果你想在一行中声明两个或更多指针更好地使用(b)变体,因为它很清楚你想要什么.往下看:
int *a;
int* b; // All is OK. `a` is pointer to int ant `b` is pointer to int
char *c, *d; // We declare two pointers to char. And we clearly see it.
char* e, f; // We declare pointer `e` and variable `f` of char type.
// Maybe here it is mistake, maybe not.
// Better way of course is use typedef:
typedef char* PCHAR;
PCHAR g, h; // Now `g` and `h` both are pointers.
// If we used define construction for PCHAR we'd get into problem too.
Run Code Online (Sandbox Code Playgroud)
妥协是
char * p;
Run Code Online (Sandbox Code Playgroud)
K&R使用
char *p;
Run Code Online (Sandbox Code Playgroud)
除非您遵循编码标准,否则由您决定 - 在这种情况下,您应该遵循其他人所做的事情.