according to some tutorials i read a while back, the \"const\" declaration makes a variable \"constant\" ie it cannot change later.
But i find this con
People usually face this problem when they start using the const keyword. Believe me, it really helps. Leave it to the compiler to take care of the cosntness of the variable, instead of you taking care to not alter its value anywhere.
Are you serious? Why would you want to give up on such a useful feature just because you make a mistake sometimes? Better try and learn to avoid mistakes with const
and you benefit from the great assistance it adds to ensure correctnes with your code.
Of course, you can say goodbye to all the help the language provides, and tell the compiler thereby not tell you about mistakes in your code anymore. Instead, you will have to ask the debugger later on where your bugs are. Not sure whether that's better.
The idea behind using 'const' is specifically that you ensure compiler errors when attempting to alter a variable's value when it has been predetermined (by using const
) that you do NOT want to do so. It's essentially built in error-checking, and is useful for many reasons.
This is especially valuable in cases such as an external interface and public methods as a way of guaranteeing the caller that a passed value will not be modified.
const
also locks in the intent to not modify, and prevents accidental assignment.
While making const
use mandatory is unnecessary, it is very useful and good practice.
Here's a useful explanation you may want to check out: http://duramecho.com/ComputerInformation/WhyHowCppConst.html
Even if you and everyone you work with never makes mistakes, the use of const in your method declarations helps to document your interface.
You can forget about it but isn't it nice if the compiler forces it upon you? That way, your "const" variables actually stay constant.