Home > Back-end >  How do I make a function execute a task when it ends?
How do I make a function execute a task when it ends?

Time:10-15

I have a function that I wish to be called infinitely as long as conditions are met. However, I cannot simply call the function inside of itself, as that will cause a stack overflow. How do I end the function and start another one at the same time?

Example:

int myFunc() {
    //do stuff
    char again;
    std::cout << "Do it again?\n";
    std::cin >> again;

    //I want to do this, but in a way that ends the function first.
    if (again = y) {
        myFunc();
    }
}

CodePudding user response:

Well you haven't given any code example, so I'm probably out on a limb here, but I'm guessing you have something like this:

void my_func()
{
    // do stuff
    // ...

    while (cond)
    {
        my_func();
    }
}

There's two ways you can fix this:

1)

// this is wherever you call my_func
void some_other_func()
{
    while (cond)
    {
        my_func();
    }
}

void my_func()
{
    // do stuff
    // ...
}
  1. (better, you only have to edit my_func to call a private implementation of the actual method part)
void my_func_impl()
{
    // do stuff
    // ...
}

void my_func()
{
    while (cond)
    {
        my_func_impl();
    }
}

EDIT

Now that you posted an example, this is how I'd refactor your code to accomplish this:

void doIt() {
    // do stuff
}

void myFunc() {
    //do stuff
    char again;

    while (1) {
        std::cout << "Do it again?\n";
        std::cin >> again;

        if (again = y) {
            doIt();
        }
        // if the answer wasn't yes, the if case won't enter
        // break the loop in that case
        break;
    }
}

CodePudding user response:

int myFunc() {
  char again;
  do {
    std::cout << "Do it again?\n";
    std::cin >> again;
    
  } while (again == 'y');
}
  • Related