Possible Duplicate:
Constants and compiler optimization in C++
Let the holy wars begin: I've heard a number of differing opinions on the usefulness of const in C++. Of course it has uses in member function declarations, etc. But how useful is it as a modifier on variables (or rather, constants)? Does it indeed help the optimizer, if the rest of the code is left the same?
const correctness can't improve performance because const_cast and mutable are in the language, and allow code to conformingly break the rules. This gets even worse in C++11, where your const data may e.g. be a pointer to a std::atomic , meaning the compiler has to respect changes made by other threads.
const can't be optimized because there may be other mutable references to the same memory object. But for immutable references, there cannot be. It is possible to cast away const and immutable in D, but these are only allowed in system code, presumably where the programmer actually does know what he's doing.
The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it. In C, constant values default to external linkage, so they can appear only in source files.
The const ness of arguments doesn't impact rather or not a copy is made. The fact that it's taken by value is what makes a copy.
There are a lot of cases where the const modifier won't help the optimizer, for the simple fact that the compiler can already tell if you modified a variable or not. The biggest benefit of const, in my opinion, is that it tells the compiler whether the programmer intended to modify that variable, which is useful in finding certain types of semantic errors at compile time instead of run time. Any error you can move to compile time is a huge boost in programmer productivity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With