Chris
Chris

Reputation: 8412

Exit C function cleanly

I have a couple of functions. Basically a menu where a user can choose 1-n different options, and each of those options have a function associated with them. In this example it's been dumbed down.

What I am trying to determine is the best way to exit a function prematurely. For example, when the user presses enter whilst in the function of a menu option, I want the program to send them back to the menu without running anything else in that function.

In the case below, I simply call showMenu() and place a return statement after it. The only thing is, if the user quits multiple functions there will be a trail of return statements that needs to be unraveled at the end.

Could somebody please show me if there is a more efficient way to achieve this or whether I am on the money.

void showMenu()
{
   //Display menu

   //Prompt user for menu option

   //Run function of appropriate menu option
   runSelectedFunction();
} 

void runSelectedFunction()
{
   //Get user input for the function and validate

   //Check if the user input was only a '\n' if so show the menu and exit
   showMenu();
   return;

   //Do the stuff that this function is meant to do.
}

Upvotes: 0

Views: 434

Answers (3)

Ben
Ben

Reputation: 1359

An alternative is to use the following pattern to ensure your function always returns from one place, giving you the opportunity to always free resources (or report errors, etc):

int func(void)
{
    int ret = 0;

    do
    {
        if (!allocate_resource())
        {
            ret = -1;
            break;
        }

        if (!allocate_more_resources())
        {
            ret = -2;
            break;
        }

        do_stuff();
    }
    while (0);

    free_allocated_resources();

    return (ret);
}

Upvotes: 0

Demian Brecht
Demian Brecht

Reputation: 21368

The best way? In short, don't.

Why?

Although there's nothing technically wrong with it and you'll find it all over the place, it can sometimes lead to headaches when trying to track down bugs or memory leaks in complex code.

Use early returns only when absolutely necessary and even then try to find an alternative first :)

Upvotes: 0

Mario The Spoon
Mario The Spoon

Reputation: 4859

Looks good to me. Or - since there are many around that are against having multiple exit points form a single function - you could do:

void func()
{
   //get input

   if ( checkMenu() )
   {
      //do the stuff I am meant to do
   }
   else
   { 
      showMenu();
   }
}

so you are avoiding adding a second return to your function. Also you could have the showMenu() call always at the end of the function, depending on your needs

hth

Mario

Upvotes: 4

Related Questions