Any good idioms for error handling in straight C programs?

后端 未结 12 1535
梦如初夏
梦如初夏 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:55

    Provided you are working with a specific context, I think the following pattern is very nice. The basic idea is that operations on an error-set state are no-ops, so error checking can be postponed to when it is convenient!

    A concrete example: A deserialization context. Decoding of any element can fail, but the function may continue without error checking because all the decode_* functions are no-ops when the serialization record is in an error state. It's a matter of convenience or opportunity or optimization to insert decode_has_error. In the example below, there is no error check, the caller will take care of that.

    void list_decode(struct serialization_record *rec,                       
                     struct list *list,                                     
                     void *(*child_decode)(struct serialization_record *)) {
        uint32_t length;                                                             
        decode_begin(rec, TAG);                                  
        decode_uint32(rec, &length);                                          
        for (uint32_t i = 0; i < length; i++) {                                
            list_append(list, child_decode(rec));
        }                                                                        
        decode_end(rec, TAG);
    }
    

提交回复
热议问题