2

I was wondering if it might be sort of advantageous for a c++ compiler if there's only one return statement in a function. one of my ex-bosses once told me so but I don't get the point if there would be any difference between declaring a return variable or simply having multiple return statements, e.g. in a switch-case statement.

So my question is: is there any difference, maybe in quality, performance or stack memory savings?

tai
  • 477
  • 1
  • 5
  • 16
  • 1
    See [Return Value Optimization](https://en.wikipedia.org/wiki/Return_value_optimization) --> [*Copy Ellision in C++17*](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0135r0.html) – WhiZTiM Mar 30 '17 at 12:52
  • My not try both, compile with optimizations, and check the assembly? – NathanOliver Mar 30 '17 at 12:55
  • @NathanOliver because I never managed to get used to assembler code until now (and wouldn't know how even) - how could I check that? – tai Mar 30 '17 at 13:23
  • Here is a very good tool: https://gcc.godbolt.org/ – NathanOliver Mar 30 '17 at 13:25
  • that one's really great, thanks a lot @NathanOliver – tai Mar 30 '17 at 13:31

5 Answers5

4

Ideally, you always want one return statement, as this ensures that your code will ALWAYS return a value, and you set that value before returning it, such as:

int getNumber(int x){
    int toReturn = 0;
    if (x == 0){
        toReturn = 5;
    } else {
         toReturn = 10;
    }
    return toReturn;
}

If you were to return in the "if" statement, then you would also have to return in the "else" statement, and if you ever wanted to add more cases, you'd have to add more "return" statements - which could prove to be very confusing if you have a multitude of cases, and could eventually impact your compile time if you're not careful.

However, there are some times when you definitely want more than one return statement. This occurs when there is some further operation that you want to stop - such as in recursion, or in scoring algorithms that have some sort of threshold for one or more parameters that disqualifies the object being scored.

For example, if you want to score something based on its distance, but you always want the score to be zero if the distance is less than ten, then:

float scoreObject(float distance){
    if(distance < 10){
        return 0;
    }
    float score;
    //Scoring function continues here, presumably with some time-intensive
    //calculations that the above return statement avoids doing.
    return score;
    //Please note that this would result in a crash as score is not initialized.
}
  • Is there still a way to do this if you want to return the value by reference? I don't see a way around multiple return statements if you are returning different values by reference, since you can't declare a reference variable without initializing it as well. – Kyle Anderson Feb 26 '20 at 15:11
2

Don't write code to suit your compiler. That changes with every compiler and compiler version. What is true today might be wrong tomorrow. Write code so it readable and shows what you intent.

As for multiple returns I highly doubt that makes any difference at all. As for trying, compiling and profiling be very aware that optimization is highly suspect to context. Multiple returns might be twice as fast in your test case but half as fast in the next function, if it shows a difference at all. To get a reliable comparison you have to test many different functions and places they are used. But if you compile the two and get the same or nearly same assembler that is a good indication that the compiler really doesn't care.

Goswin von Brederlow
  • 11,875
  • 2
  • 24
  • 42
1

No, not really.

I do actullay like having many return values. It simplify's the code greatly and I have found no problem with it. Visual Studio, the IDE that I use, handles it with no problem.

Dat Ha
  • 562
  • 1
  • 9
  • 16
1

This issue might be related to return value optimisation - Compiler wont create the returned variable as a local variable and do a assignmen/copy construction as the function hits the return statement, rather it will build the variable in the memory address of the variable to which the value would be assigned.

You can have multiple return statements and it should not matter, if you are returning the same variable. However if you have multiple variables in your function and you return then differently depending on the code flow the compiler cannot perform such optimisation.

Lets have the following assignment

string str;
str = make_name(2);

Compiler might perform RVO in the following code

string make_name(int num){
    string result = "Simon";
    if (num & 1){
        result.append(" Hrabec");
        return result;
    } else {
        result.append(" John");
        return result;
    }
}

However in this code the compiler cannot say which variable should build in the location of the variable that is having a new value assigned. During the function evaluation both can live at the same time, being updated and the decision which one should be returned can be made at the end.

string make_name(int num){
    string result1 = "Simon Hrabec";
    string result2 = "Simon John";
    if (num & 1){
        return result1;
    } else {
        return result2;
    }
}

However I do not imply to use such programming style.

Šimon Hrabec
  • 626
  • 1
  • 7
  • 10
0

Refer https://en.wikipedia.org/wiki/Return_statement sub-section Multiple return statements

  • Whilst this may theoretically answer the question, [it would be preferable](//meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference. – Olaia Mar 30 '17 at 13:35