Any good idioms for error handling in straight C programs?

Posted by Will Hartung on Stack Overflow See other posts from Stack Overflow or by Will Hartung
Published on 2010-05-07T16:11:39Z Indexed on 2010/05/07 16:18 UTC
Read the original article Hit count: 148

Filed under:
|

Getting back in to some C work.

Many of my functions look like this:

int err = do_something(arg1, arg2, arg3, &result);

With the intent the result gets populated by the function, and the return value is the status of the call.

The darkside is you get something naive like this:

int err = func1(...);
if (!err) {
    err = func2(...);
    if (!err) {
        err = func3(...);
    }
}
return err;

I could macro it I suppose:

#define ERR(x) if (!err) { err = (x) }
int err = 0;
ERR(func1(...));
ERR(func2(...));
ERR(func3(...));
return err;

But that only works if I'm chaining function calls, vs doing other work.

Obviously Java, C#, C++ have exceptions that work very well for these kinds of things.

I'm just curious what other folks do and how other folks do error handling in their C programs nowadays.

© Stack Overflow or respective owner

Related posts about c

    Related posts about error-handling