Should variable declarations always be avoided in C ++?

advertisements

Sometimes I declare "one use" variables in my code for clarity. Does this affect dramatically the performance or can the compiler optimize it?

For example, I would tend to do:

int minVal = long_arithmetic_expresion();
int maxVal = even_longer_expression();

for (int i = minVal; i < maxVal; i++)
    {
        // Do stuff not related to minVal or maxVal
    }

double part1 = 4*sqrt(something)* ... // Very long thing
double part2 = 5*sqrt(something else)* ... // Very long thing

double interestingValue = part1 / part2; // This is the only interesting variable for later

Rather than:

for (int i = long_arithmetic_expresion(); i < even_longer_expression(); i++)
    {
        // Do stuff not related to minVal or maxVal
    }

double interestingValue = (4*sqrt(whatever)* ...) / (5*sqrt(something else)* ...);

This for loop would be contained in a function that will be called many times, so even small performance gain would be relevant in my case.

Note:

As it was quickly pointed out, there is a chance that even_longer_expression() could be evaluated at every step of the loop, which is of course not good. For clarity, my question relates to the fact of declaring one-use variables. I have added a bit more code after the loop. I refer to cases like the variables part1 and part2.


Does this affect dramatically the performance or can the compiler optimize it?

Totally depends:

If long_arithmetic_expresion() and even_longer_expression() are marked as constexpr and not likely to change during runtime, the compiler can optimize out recurring calls to these functions.

Otherwise it might be better to use the variables being initialized once.