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