Say I had this snippet of code:
#include <cmath>
// ...
float f = rand();
std::cout << sin(f) << " " << sin(f);
As sin(f) is a well defined function there is an easy optimisation:
float f = rand();
float sin_f = sin(f);
std::cout << sin_f << " " << sin_f;
Is this an optimisation that it’s reasonable to expect a modern C++ compiler to do by itself? Or is there no way for the compiler to determine that sin(f) should always return the same value for an equal value of f?
Using g++ built with default optimization flags:
Built with
-O2:From this we can see that without optimizations the compiler uses 2 calls and just 1 with optimizations, empirically I guess, we can say the compiler does optimize the call.