使用C switch语句进行错误处理

0x6*_*015 0 c error-handling goto

考虑这个在实际工作之前检查错误的C结构:

int function(struct Context *context,struct Connection *conn)
{
    int retval;

    switch(0)
    {   
        case 0:
            retval = BUFFER_INACTIVE;
            if(conn->mSocket == -1) 
                break;
            retval = BUFFER_FULL;
            /* Is there enough room to add ? */
            if((context->mMaxBufferSize - conn->mSendPacketLength) < aPacketLength)
                break;

            /* Is the send packet buffer half sent? */
            if(conn->mSendPacketLength > 0 && conn->mSendPacketPos != conn->mSendPacket)
                break;

            /* Do some work here */
            retval = BUFFER_DONE;
    }
    /* Do some things before returning */
    printf("%d",retval);
    return retval;
}
Run Code Online (Sandbox Code Playgroud)

你认为这是可读的吗?使用goto或堆叠的替代品if()会更好吗?

Gra*_*row 5

我从未见过切换解决方案,但我做过这样的事情:

do {
    err = func();
    if( err ) break;
    err = func2();
    if( err ) break;
    ...
} while( 0 );
if( err ) {
   // handle errors
}
Run Code Online (Sandbox Code Playgroud)

但是这和它之间的真正区别是什么:

err = func();
if( err ) goto done;
err = func2();
if( err ) goto done;
...
done:
if( err ) {
   //handle errors;
}
Run Code Online (Sandbox Code Playgroud)

第一个是为了避免使用关键字goto而重写的第二个,我认为goto解决方案更具可读性.我花了一段时间,但我设法说服自己,goto并不总是邪恶.

最后,if如果可能的话,我更喜欢使用语句,因为它使代码更具可读性,但goto必要时也是如此.