Let's start with the non const approachThe non-const approach:
Here the compiler has to assume that k could be changed by f()f(), because this function is unknown. So the generated code has to make the calculation of ii, even if we'd know that f() doesn't change the value pointed at.
Now the same code with const approach would look like:The const approach:
First of all, the const_castconst_cast shows that we are taking a risk. So we have to be really sure that f()f() will not change the value pointed at (if not it would be undefined behavior).
The clean const approach:
Of course const_castconst_cast is something risky, and should be avoided if possible. And that's where the second level benefit of using const appears: you become sensitive to this kind of subtleties, and you'll start increasing const discipline, rewriting the ff() properly by making constness explicit as well:
This code is event better, because not only are you sure that k is constant, but everybody now knows that f() doesn't change the pointed value, and the compiler can do better constant propagation.