Sign in to follow this  
roos

Do C++ compilers optimize intermediate variables?

Recommended Posts

Hi, I read an article on self-documenting code recently, and one point they made is that intermediate variables can help to make it more accurate and readable. For example, replace: float radiusSquared = maxExtent * 1.41f; radiusSquared *= radiusSquared; with: float radius = maxExtent * 1.41f; float radiusSquared = radius * radius; The advantage of the 2nd one is that it's more precise... The 1st one can be a little confusing because the 1st line of code is setting "radiusSquared" equal to a value which is actually just the radius. In an example like this, the intent is clear but I can imagine it would become problematic in a more hairy piece of code... So my question is, is it okay to use intermediate values like this? Is the compiler clever enough to optimize away intermediates so that the 2nd example would be as efficient as the first one? Thanks, roos

Share this post


Link to post
Share on other sites
The rule of thumb with modern compilers is that they are smarter optimizers than you. So yes, the one or two cylces that you are trying to save will most likely be saved or even improved upon by the compiler. Your best bet is to set the compiler to out put assembly and compile those two examples and compare the two.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this