Question

When we have functions, the return statement allows us to prematurely exit from the function. Even for a function with no return type, we can use return to exit the current function.

My question is: Is it a good coding practice to use return to exit from the function to go back to the point where the function is called?

One good example of such scenario is a main menu with sub menu.

Example:

//Decalration
void mainMenu(); 
void subMenu(); 

int main()
{
    mainMenu();
    return 0;
}

//Definition
void mainMenu();
{
    //some codes
    subMenu();
}

void subMenu();
{
    int option;
    cout << "Choose 1 to return to main menu" << endl;
    cout << "Choose 2 to do whatever..." << endl;
    cin >> option;
    if (option == 1)
        return;    //Return to main menu (<--- Is this a good coding practice?)
    else
        //some codes
}

Note: I am not asking for help in assignment. This is a working code, I just want to know whether using return statement to go back to the point of calling a correct practice? If not, what should be the correct way to return to the point of calling.

Was it helpful?

Solution

C and C++ are different in this regard.

In C, early returns can easily cause cleanup (or even critical business code) to not be performed, especially after the code has been maintained for some time.

In C++ one has to code with the possibility of early exits always in mind, due to the use of exceptions. And so multiple returns are not problematic in good C++ code. Cleanup is performed automatically by destructors, C++ "RAII".


From there, it's a matter of personal preference, project coding guidelines, etc.


Regarding your code example,

void subMenu();
{
    int option;
    cout << "Choose 1 to return to main menu" << endl;
    cout << "Choose 2 to do whatever..." << endl;
    cin >> option;
    if (option == 1)
        return;    //Return to main menu (<--- Is this a good coding practice?)
    else
        //some codes
}

one alternative is simply

void subMenu();
{
    int option;
    cout << "Choose 1 to return to main menu" << endl;
    cout << "Choose 2 to do whatever..." << endl;
    cin >> option;
    if (option != 1)
    {
        //some codes
    }
}

which causes the “exit modal context” to be more manifestly treated specially, but it was already treated specially.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top