一个变量声明中存在多个 const
我的一位同事对 ANSI C 中的 const 有点着迷,我想知道你们对此有何看法。例如,他写了这样的东西:
const uint8* const pt_data
我理解他的意图,但对我来说,这使得阅读和可维护性变得更加困难,因为所有这些常量无处不在。
A colleague of mine is going a bit nuts with const in ANSI C and I wanted to know what you guys thought about it. He writes stuff like this for example:
const uint8* const pt_data
I understand where he's going with this but for me it makes the reading and maintainability harder with all these const everywhere.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它是一个指向
const
数据的const
指针。const
防止*pt_data = 10;
const
防止pt_data = stuff;
看起来可以是相当合法的。
It's a
const
pointer pointing toconst
data.const
prevents*pt_data = 10;
const
preventspt_data = stuff;
It looks like it can be pretty legitimate.
const
总是引用其右侧的单词,除非它位于行尾,它指的是项目本身(在高级语言中)您应该在声明它们时始终初始化这些指针(除非它们是参数)
const
关键字非常适合确保某些内容不会被修改,并且还告诉开发人员不应修改。例如,int strlen(const char* str)
告诉您字符串中的char
数据不会被修改。const
always refers to the word on its right, except if it is at the end of the line, where it refers to the item itself (in higher level languages)You should always initialize those pointers when declaring them (Except if they're a parameter)
const
keyword is great at ensuring something will not be modified, and also tells the developper it should not. For exampleint strlen(const char* str)
tells you thechar
data in your string will not be modified whatsoever.它是一个指向常量数据的常量指针。
这意味着您无法更改数据(其地址
pt_data
存储),也无法更改指针(pt_data
)以指向其他内容(其他地址)。他可能需要这样。
It is a constant pointer to an constant data.
it means you cannot change the data(whose address
pt_data
stores) and also cannot change the pointer(pt_data
) to point to something else(some other address).He probably needs it that way.
如果从变量名称开始,逆时针方向,
pt_data
是一个const
指针,指向uint8
,即const
代码>.请看下面的粗略 ASCII 图像:
自从我多年前在一本旧 C 书中看到这个方案以来,它帮助我理解了复杂的声明。
If you start at the variable name, and going counter-clockwise,
pt_data
is aconst
pointer touint8
which isconst
.See the following crude ASCII image:
Ever since I saw this scheme in an old C book many years ago, it has helped me understand complex declarations.