检查大量返回值时的好c风格

Wan*_*ang 11 c coding-style

有时我必须编写代码,在执行操作和检查错误条件之间交替(例如,调用库函数,检查其返回值,继续).这通常导致长期运行,其中实际工作发生在if语句的条件下,例如

if(! (data = (big_struct *) malloc(sizeof(*data)))){
    //report allocation error
} else if(init_big_struct(data)){
    //handle initialization error
} else ...
Run Code Online (Sandbox Code Playgroud)

你们是怎么写这种代码的?我检查了一些样式指南,但他们似乎更关心变量命名和空格.

风格指南的链接欢迎.

编辑:如果不清楚,我不满意这种风格的易读性,并寻找更好的东西.

Fre*_*son 15

虽然我很难说,但这可能是一个从未流行的案例goto.这是我在这个主题上找到的一个链接:http://eli.thegreenplace.net/2009/04/27/using-goto-for-error-handling-in-c/


Mau*_*lli 13

我通常以这种方式编写代码:

data = (big_struct *) malloc(sizeof(*data));
if(!data){
    //report allocation error
    return ...;
}

err = init_big_struct(data);
if(err){
    //handle initialization error
    return ...;
}

...
Run Code Online (Sandbox Code Playgroud)

通过这种方式,我可以避免调用函数,如果调试更容易,因为您可以检查返回值.