Do C++ compilers optimize intermediate variables?

Started by
2 comments, last by roos 19 years, 4 months ago
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
Advertisement
Yes.

The two snippets will almost certainly compile to exactly the same code. They do on my compiler.
CoV
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.
Lucas Henekswww.ionforge.com
Good deal :) Thanks!

This topic is closed to new replies.

Advertisement