What is the benefit of the const keyword in programming? [duplicate]

南楼画角 提交于 2019-12-13 09:49:31

问题


Possible Duplicate:
Sell me on using const correctness

I'm eager to know the answer. [to "What is the benefit of const keyword in programming?"]


回答1:


const indicates that the value assigned to the variable cannot change. If you try to change the value you should get a compiler error.




回答2:


The const keyword can declare a read only variable.

Using const parameters to a method tells you the method will not change the parameter.

A const method tells you that the method will not alter a class's member variables (but can change member variables marked as mutable)

You can also declare const pointers, better described here




回答3:


What is the benefit of const keyword in programming?

Specifying a variable as const states that the variable's value should never change after the initial assignment. This allows the compiler to perform additional tests at compilation (validating your code).

For example, if a const function changes a (non-mutable) member in an object, the compiler will yield an error.




回答4:


Benefit: You get more compile time checks to ensure that you're not changing data that shouldn't be changed.

Cost: You have to use it everywhere. If you need to, you can cast your way out of it, nullifying the benefits.

Getting usage right can be tricky with pointers. Is the pointer itself const, or the data it refers to? This is also the most common usage I've seen: you want to point to immutable memory.



来源:https://stackoverflow.com/questions/3263506/what-is-the-benefit-of-the-const-keyword-in-programming

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!