For instance, if I have this code:
class SomeDataProcessor { public: bool calc(const SomeData & d1, const SomeData & d2) const; private: //Some non-mutable, non-static member variables } SomeDataProcessor sdp; SomeData data1; SomeData data2; someObscureFunction(sdp.calc(data1, data2), sdp.calc(data1, data2));
Let's consider the potentially equivalent code:
bool b = sdp.calc(data1, data2); someObscureFunction(b,b);
For this to be valid, the calc()
function should meet some requirements, and for the example I call the property _pure_const_formula_
A _pure_const_formula_
would:
_pure_const_formula_
functionsFor instance, calling a random number generator would not fit these requirements.
Is the compiler allowed to replace the first code with the second one, even if it needs to dig recursively into called functions? Are modern compilers able to do this?
When you declare a const in your program, int const x = 2; Compiler can optimize away this const by not providing storage for this variable; instead it can be added to the symbol table. So a subsequent read just needs indirection into the symbol table rather than instructions to fetch value from memory.
No, const does not help the compiler make faster code.
The const keyword allows you to specify a semantic constraint: an object should not be modified. And compilers will enforce that constraint. This will allow you to communicate to the compiler and to other developers that the object should remain invariant.
It is recommended the practice to make as many functions const as possible so that accidental changes to objects are avoided.
GCC has the pure
attribute (used as __attribute__((pure))
) for functions which tells the compiler that redundant calls can be eliminated. It's used e.g. on strlen
.
I'm not aware of any compiler doing this automatically, especially considering the fact that the functions to be called may not be available in source form, and the object file formats contain no metadata about whether a function is pure or not.
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