Saving a value before returning to a variable

Here is the code snippet:

bool EqualsA(const Foo& a, const Foo& b) { return a == b; } bool EqualsB(const Foo& a, const Foo& b) { const bool result = a == b; return result; } int MethodA() { return GetValue() * GetOtherValue(); } int MethodB() { const int result = GetValue() * GetOtherValue(); return result; } 

I wanted to know if there is a difference in returning values ​​in these two different ways (instantly returning or storing the result in a variable). I think storage is better for debugging, but is there a loss of performance (I don’t think there is) or any other pros and cons for using one of them.

0
c ++ coding-style return return-value
source share
3 answers

The compiler can optimize the local variable so that the performance is the same.

In many code analysis tools, this is noted as a smell of code, and I would agree. Debuggers can be made to see the return value on the stack so that the local variable does not buy anything.

+4
source share

Under the reasonable assumption that the value returned by the selected operator == overload for objects of type Foo is of type bool , a decent compiler will optimize your temporary store when large optimization parameters are used, so as far as performance is concerned, it does not matter .

My advice is to choose a form that will make your code more readable or more convenient for you or debugging.

+3
source share

There will almost certainly be no difference. The compiler is allowed to do everything that he likes for your code, while the program behaves as if, if you wrote it. Therefore, any good compiler will get rid of senseless initializations.

However, it is possible that the situation cannot lead to this initialization disappearing. If, for example, the operator* overload used for GetValue() * GetOtherValue() returns a class type result using a const reference, the constructor of this class type may have some side effects. If so, the compiler cannot get rid of the initialization, since it changes the observed behavior of the program.

But why is this not the case if operator* returned by value? Then it will be a candidate for copying elitia, and the compiler can get rid of the construct regardless of whether it had side effects or not.

+1
source share

All Articles