Christian
Christian

Reputation: 593

Should I use returning functions when the return value isn't needed?

I have a function that looks like this:

int Game::GetInput() {
    while (true) {
        // do stuff
        if (something) {
            // do this
            return 0;
        }

        else {
            // do other stuff
        }
    }
}

I'm wondering if it is common or proper to have a returning function, rather than a void function, for the sole purpose of leaving the function (the value being returned wouldn't do anything in the program except for ending the function). Is this good practice, or is there a better way to end a function?

Upvotes: 0

Views: 119

Answers (4)

Jonathan Leffler
Jonathan Leffler

Reputation: 754160

If there is no useful value for the function to return, it is better not to return a value - because the calling code should check the returned value.

Your code can be doubly simplified:

void Game::GetInput() {
    while (true) {
        // do stuff
        if (something) {
            // do this
            return;
        }
        // do other stuff
    }
}

The else is unnecessary; the only way to execute the 'do other stuff' is if something is false.

Upvotes: 0

Squall
Squall

Reputation: 4472

There is no problem with void functions. If it does not return anything useful, it should be void.

Upvotes: 3

Matthew Scharley
Matthew Scharley

Reputation: 132314

You can easily just use return; with no parameter to exit a void function. Your above code would become:

void Game::GetInput() {
    while (true) {
        // do stuff
        if (something) {
            // do this
            return;
        }

        else {
            // do other stuff
        }
    }
}

Upvotes: 1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272557

Just make your function void, and simply return?

// vv void return type
void Game::GetInput() {
    while (true) {
        // do stuff
        if (something) {
            // do this
            return;  // <<<< No return value
        }

        else {
            // do other stuff
        }
    }
}

Upvotes: 1

Related Questions