开发者

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

This question already has answers here: 开发者_JAVA百科 Closed 12 years ago.

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?"]


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


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜