C++: reasons to return void and/or return early

I was recently refactoring some code, leaving a function in which the most natural thing was to return a call to a void function. The code structure was like this simplified example, where I wanted to return early from a nested if statement, but it felt clumsy to put bar() and return on separate lines:

void bar()
{
    printf( "bar\n" );
}

void foo( int a, double b )
{
    if ( a > 0 )
    {
        double c = a * b;
        if ( c > 0 && c > a )
        {
            return bar();
        }
    }

    printf( "foo\n" );
}

I was surprised that this worked, because I half expected the compiler to do something sinister like optimise out the call to bar(), given that it returns void and only executes useful code via side-effects.

This post asks the same question, but it seems that this is supported in C++ and can be useful for template functions that return void.

Some readers may take issue with the early return in the code above. I admit I used to follow the mantra of maintaining a single return point in any function (except perhaps an early return after checking pre-conditions on parameters). However, the modern C++ take on this is that early returns are recommended and may lead to faster code. Herb Sutter has this to say:

allowing the function itself to return early when it knows it’s done is perfectly fine and fully under the function’s control. To put the final nail in the coffin, note that “single exit” has always been a fiction in any language that has exceptions, because you can get an early exceptional return from any point where you call something that could throw an exception

.

Leave a comment

Filed under C++

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.