Use of const double for intermediate results

Posted by Arne on Stack Overflow See other posts from Stack Overflow or by Arne
Published on 2010-05-25T12:22:05Z Indexed on 2010/05/25 12:31 UTC
Read the original article Hit count: 398

Filed under:
|

Hi,

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

© Stack Overflow or respective owner

Related posts about c++

Related posts about const