I often use const for local variables that are not being modified, like this:
const float height = person.getHeight();
I think it can make the compiled code potentially faster, allowing the compiler to do some more optimization. Or am I wrong, and compilers can figure out by themselves that the local variable is never modified?
Most of the compilers are smart enough to figure this out themselves.
You should rather use
constfor ensuring const-correctness and not for micro-optimization.const correctness lets compiler help you guard against making honest mistakes, so you should use
constwherever possible but for maintainability reasons & preventing yourself from doing stupid mistakes.It is good to understand the performance implications of code we write but excessive micro-optimization should be avoided. With regards to performance one should follow the,
80-20 Rule: