am*************@gmail.com wrote:
Can you please tell me what uses for constants I am missing?
Constants have basically two purposes: They are small guards against
bugs, and sometimes the compiler can perform certain optimizations when
using constants which it can't do with non-constants. (Of course there
is also the few cases where a constant is required as per C++ syntax,
such as for example when defining the size of an array.)
Personally I *always* use 'const' with everything which is not
intended to be changed. I use it even with temporary variables which
contain temporary calculation results inside functions. Basically what
I'm saying to the compiler with that is "this is something I don't want
to change, if I accidentally attempt to do so, tell me". Usually if an
attempt to change a constant is made, that's a programming error made by
mistake, and it's much better to catch those at compile time than at
testing. Better use 'const' by default, and remove it later if you
really need to change it after all, than the other way around.
Besides this, the compiler can sometimes generate faster code when
variables which don't change have been declared const, which is always a
plus, and certainly doesn't hurt. Basically you are getting faster code
by making your code cleaner and safer. The best of both worlds.