Any good idioms for error handling in straight C programs?

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

    Something I've recently seen is this idom:

    int err;
    do 
    {
      err = func1 (...);
      if (!err) break;
    
      err = func2 (...);
      if (!err) break;
    
      err = func3 (...);
      if (!err) break;
    
      /* add more calls here */
    
    } while (0);
    
    if (err)
    {
      /* handle the error here */
      return E_ERROR; /* or something else */
    }
     else 
    {
      return E_SUCCESS;
    }
    

    Pro arguments:

    It avoids the goto (abuses the while(0) / break combination for that). Why would you want to do this? It keeps the cyclomatic complexity down and will still pass most static code analyzer checks (MISRA anyone?). For projects that get tested against cyclomatic complexity this is a god sent because it keeps all the initialization stuff together.

    Contra arguments:

    The meaning of the do/while loop construct is not obvious because a loop-construct is used as a cheap goto replacement, and this can only be seen at the loop tail. I'm sure for the first time this construct will cause lots of "WTF"-moments.

    At least a comment is necessary to explain why the code is written the way it is required.

提交回复
热议问题