const
does not help the optimizer.
Since const
can be cast away with const_cast
, it's possible to write programs that use const
in a number of places, then cast it away and modify variables anyway, with defined behavior according to the standard. The compiler therefore must look at the actual code of the program to determine which variables are modified when, and it's probably pretty good at this anyway (for example it might determine a non-const variable is invariant over a certain block of code and optimize accordingly).
If the compiler blindly treated const
as a guarantee that something won't change, the optimizer would break some well-formed programs.
const
is a compile-time feature to help programmers write correct code, by adding some compile-time constraints, and indicating a code contract (eg. 'I promise not to change this parameter'). It has nothing to do with optimization. While invariants are important to optimizers, this has nothing to do with the const
keyword.
There is one exception: objects declared with const
. These cannot be modified; even if they are via casting, the behavior is undefined. There's some subtlety here:
const int ci = 5;
const_cast<int&>(ci) = 5; // undefined behavior, original object declared const
int i = 5;
const int& ci2 = i; // cannot modify i through ci2, const reference
const_cast<int&>(ci2) = 5; // OK, original object not declared const
So when the compiler sees const int ci
it probably does assume it will never, ever change, because modifying it is undefined behavior. However, chances are this isn't the bottleneck in your program, it's just a more sophisticated #define
. Apart from that, const
is weak - just a keyword for the type system.