在C / C声明指针变量的正确方法+ [英] Correct way of declaring pointer variables in C/C++

查看:163
本文介绍了在C / C声明指针变量的正确方法+的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到一些人使用下面的符号来声明指针变量。

I noticed some people use the following notation for declaring pointer variables.

(a) char* p;

而不是

(b) char *p;

我用(B)。什么是符号(一)背后的理性?
符号(B)更有意义,我是因为字符指针不是一个类型本身。代替的类型是字符,变量可以是指向字符

I use (b). What is the rational behind the notation (a)? Notation (b) makes more sense to me because character pointer is not a type itself. Instead the type is character and the variable may be a pointer to the character.

char* c;

这貌似有一个char *类型和变量c是该类型的。但实际上类型为char和* C(c所指向的内存位置)是类型(炭)的。如果您一次这种区别就显而易见声明多个变量。

This looks like there is a type char* and the variable c is of that type. But in fact the type is char and *c (the memory location pointed by c) is of that type (char). If you declare multiple variables at once this distinction becomes obvious.

char* c, *d;

这看起来很奇怪。无论c和d同一种指向一个字符指针。在此,因为下一个看起来更自然。

This looks weird. Both c and d are same kind of pointers that point to a character. In this since the next one looks more natural.

char *c, *d;

感谢。

推荐答案

Bjarne的Stroustrup的说:

Bjarne Stroustrup said:

之间的选择诠释* P;和INT * P;是不是对与错,而是风格和强调。 ç强调前pressions;声明常常被认为比必要之恶而已。 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.

一个典型的C程序员写道:诠释* P;并解释为* p是什么是诠释强调语法,以及可能指向C(和C ++)声明语法主张风格的正确性。事实上,*结合在语法名称第

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.

一个典型的C ++程序员写道:诠释* P;并解释为p是一个指向一个int强调类型。的确p的类型是int *。我清楚地preFER的重视,并看到它使用C ++更先进的部分以及重要的。

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.

来源:<一个href=\"http://www.stroustrup.com/bs_faq2.html#whitespace\">http://www.stroustrup.com/bs_faq2.html#whitespace

我建议后者风格,因为在你的声明在一行(你的第4个例子)多个指针,具有可变星号将是你习惯了什么情况。

I'd recommend the latter style because in the situation where you are declaring multiple pointers in a single line (your 4th example), having the asterisk with the variable will be what you're used to.

这篇关于在C / C声明指针变量的正确方法+的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆