Any good idioms for error handling in straight C programs?

后端 未结 12 1510
梦如初夏
梦如初夏 2020-12-23 14:19

Getting back in to some C work.

Many of my functions look like this:

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

With th

12条回答
  •  自闭症患者
    2020-12-23 14:49

    If you have resources that need to be released at the end, then sometimes the old trusty goto can be handy!

    int
    major_func(size_t len)
    {
        int err;
        char *buf;
    
        buf = malloc(len);
    
        if (err = minor_func1(buf))
            goto major_func_end;
        if (err = minor_func2(buf))
            goto major_func_end;
        if (err = minor_func3(buf))
            goto major_func_end;
    
    major_func_end:
        free(buf);
        return err;
    }
    

提交回复
热议问题