Search code examples
c++returnstatements

using multiple return statements in a c++ function


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?


Solution

  • 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.
    }