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

标签 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;
}

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

最佳答案

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

do {
    err = func();
    if( err ) break;
    err = func2();
    if( err ) break;
    ...
} while( 0 );
if( err ) {
   // handle errors
}

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

err = func();
if( err ) goto done;
err = func2();
if( err ) goto done;
...
done:
if( err ) {
   //handle errors;
}

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

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

关于c - 使用 C switch 语句进行错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/975381/

相关文章:

perl - 黑白 goto &func; 有什么区别吗?和 &func;在 Perl 中?

perl - 在 perl 中调用 --> goto &fun($val) 或 fun($val) 哪个更有效?

c - 如何从 20 个样本中找到正弦波的幅度和频率?

c++ - 显示是/否消息框,其中“否”呈灰色 win32api C++

c - 在Linux内核中内联使用类型限定符的时机

iphone - Google新闻RSS供稿返回didFailWithError -1002代码

python - Twisted 中的 fatal error 和延迟,停止延迟

php - PHP错误处理程序/静音错误

c++ - 使用 OpenGL 中的持久映射缓冲区存储,仅在绘制之前和交换之后触及,是否真的需要任何进一步的同步?

python - Goto 的替代品,Python 中的标签?