SemicolonExpected
SemicolonExpected

Reputation: 614

Jumping back to beginning of function in C++

So I have situations where I need to break out of the current function and go back to the beginning of the function, some of these include error checking (I have not learned try, throw, or catch yet) and as of recently I've been using recursion neglecting the fact that recursion does not function like a goto and simply returns to the beginning of the function but rather creates a separate copy of itself, thus if I use recursion to catch something like client input errors, if the client makes enough errors, it could lead to a potential memory leak.

I was wondering if there was a specific function that could let me 'restart' a function.

As an example using pseudo-pseudo-code:

int foo(){
     //prompt for and receive input
     if(!matchCondition)
          //stop foo() and restart foo()
     //does something
}

The only other thing I can think of is putting the function call in a loop, but that isn't optimal if for example the function is in main() I can't exactly put the call to main in a loop within main, without creating at least one duplicate. Another example where that won't work is if the function needs to return something that doesn't have a limit and thus the "error code" can be produced naturally without the error occuring.

bool ifError=1;
while(ifError){
     ifError = foo();
}
int foo(){
     //prompt for and receive input
     if(!matchCondition)
          return 1;
     //do something
     return 0;
}

The only thing I can think of is a goto statement pointing to the line that foo() was called. if it exists, but I know that is the worst thing I can ever do.

Upvotes: 0

Views: 6744

Answers (2)

LihO
LihO

Reputation: 42103

You could do:

int foo()
{
    while (true)
    {
        ...
        if (/* this should start over */)
            continue;
        ...
        if (/* this should end */)
            return /* some value */;
        ...
    }
}

Upvotes: 1

zwol
zwol

Reputation: 140758

goto is not "the worst thing you can ever do"; in fact, there are situations where a judicious goto is more readable than any alternative.

However, this is not one of these times. I suggest you do something like this:

TYPE input_thing_from_user()
{
    TYPE rv;
    do
        rv = read_input_from_user();
    while (is_invalid(rv));
    return rv;
}

Use a separate loop for each thing to input; don't make the user retype everything if they mess up near the end of the list.

Upvotes: 5

Related Questions