I a writing a Simulation program and wondering if the use of const double is of any use when storing intermediate results. Consider this snippet:
double DoSomeCalculation(const AcModel &model) {
(...)
const double V = model.GetVelocity();
const double m = model.GetMass();
const double cos_gamma = cos(model.GetFlightPathAngleRad());
(...)
return m*V*cos_gamma*Chi_dot;
}
Note that the sample is there only to illustrate -- it might not make to much sense from the engineering side of things. The motivation of storing for example cos_gamma in a variable is that this cosine is used many time in other expressions covered by (...) and I feel that the code gets more readable when using
cos_gamma
rather than
cos(model.GetFlightPathAngleRad())
in various expressions. Now the actual is question is this: since I expect the cosine to be the same througout the code section and I actually created the thing only as a placeholder and for convenience I tend to declare it const. Is there a etablished opinion on wether this is good or bad practive or whether it might bite me in the end? Does a compiler make any use of this additional information or am I actually hindering the compiler from performing useful optimizations?
Arne
I am not sure about the optimization part, but I think it is good to declare it as const
. This is because if code is large, then if somebody incorrectly does a cos_gamma = 1
in between you will get a compiler error instead of run time surprises.
You can certainly help things by only computing the cosine once and using it everywhere. Making that result const
is a great way to ensure you (or someone else) don't try to change it somewhere down the road.
A good rule of thumb here is to make it correct and readable first. Don't worry about any optimizations the compiler might or might not make. Only after profiling and discovering that a piece of code is indeed too slow should you worry about helping the compiler optimize things.
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