HiveBrain v1.2.0
Get Started
← Back to all entries
debugcppMinor

Checking errors from a series of function calls

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
callsseriescheckingfunctionerrorsfrom

Problem

I have to work with C-style functions which return ERROR_SUCCESS when successful or an error code when not. I want my code to be nice and neat and easy to read but I am not sure I like what I have.

Option one:

int Foo()
{
    int result = Init();

    if (result == ERROR_SUCCESS)
    {
        result = SetTemperature( 30 );
    }
    else
    {
        return result;
    }

    if (result == ERROR_SUCCESS )
    {
        result = SetVoltage( 5 );
    }
    {
        return result;
    }

}


Option two:

int Foo()
{
    int result = Init();

    if (result != ERROR_SUCCESS)
        return result;

    result = SetTemperature( 30 );

    if (result != ERROR_SUCCESS)
        return result;

    result = SetVoltage( 5 );

    if (result != ERROR_SUCCESS)
        return result;

}


Please note that I can't use exceptions here. If there is an error then I simply need to return from the function with that error. Is there an even better way to organize this code?

Solution

Do your early returns properly, and there will be no more to tweak:

int Foo()
{
    int result;
    if((result = Init()))
        return result;
    if((result = SetTemperature( 30 )))
        return result;
    return SetVoltage( 5 );
}


Using the extra parentheses () around the assignment to suppress a compiler warning.

I don't check for expr != ERROR_SUCCESS because that's equivalent to expr in a boolean context.

If there are really a lot of those calls, consider investing in a preprocessor macro.

Don't forget to undefine it after use if the compilation unit is not at an end.

Also, many really don't like those.

#define OkOrReturn(a) do{int result = a; if(result) return result;}while(0)
#undef OkOrReturn

Code Snippets

int Foo()
{
    int result;
    if((result = Init()))
        return result;
    if((result = SetTemperature( 30 )))
        return result;
    return SetVoltage( 5 );
}
#define OkOrReturn(a) do{int result = a; if(result) return result;}while(0)
#undef OkOrReturn

Context

StackExchange Code Review Q#49681, answer score: 7

Revisions (0)

No revisions yet.