对局部变量使用 const
Similar to this question, what are the pro/cons to using const local variables like in this answer?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
Similar to this question, what are the pro/cons to using const local variables like in this answer?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(1)
就我个人而言,我喜欢对任何声明的对象使用 const(我不确定“变量”一词是否适用),除非我实际上要修改它。它向读者证明对象的值始终是其初始化时的值,这可以使代码更易于理解和分析。
(在某些情况下,它还可以帮助编译器,但是大多数编译器在优化模式下调用时,都足够聪明,可以注意到该对象永远不会被修改。如果您在非优化模式下调用编译器,您就是在告诉它你不太关心性能。)
事实上,如果我要设计自己的语言,默认情况下所有声明的对象都将是 const(只读)除非 您明确将它们标记为可修改。
Personally, I like to use
const
for any declared object (I'm not sure the word "variable" applies) unless I'm actually going to modify it. It documents to the reader that the value of the object is always going to be whatever it was initialized to, which can make the code easier to follow and analyze.(It can also help the compiler in some cases, but most compilers, when invoked in optimizing mode, are smart enough to notice that the object is never modified. And if you invoke the compiler in non-optimizing mode, you're telling it that you don't care much about performance.)
In fact, if I were going to design my own language, all declared objects would be
const
(read-only) by default unless you explicitly mark them as modifiable.