Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

good c style when checking lots of return values

Tags:

c

coding-style

Sometimes I have to write code that alternates between doing things and checking for error conditions (e.g., call a library function, check its return value, keep going). This often leads to long runs where the actual work is happening in the conditions of if statements, like

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

How do you guys write this kind of code? I've checked a few style guides, but they seem more concerned with variable naming and whitespace.

Links to style guides welcome.

Edit: in case it's not clear, I'm dissatisfied with the legibility of this style and looking for something better.

like image 359
Wang Avatar asked Mar 09 '10 18:03

Wang


2 Answers

Though it pains me to say it, this might be a case for the never-popular goto. Here's one link I found on on the subject: http://eli.thegreenplace.net/2009/04/27/using-goto-for-error-handling-in-c/

like image 55
Fred Larson Avatar answered Oct 06 '22 17:10

Fred Larson


I usually write that code in this way:

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

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

...

In this way I avoid calling functions inside if and the debug is easier because you can check the return values.

like image 29
Maurizio Reginelli Avatar answered Oct 06 '22 16:10

Maurizio Reginelli