Hacker News new | ask | show | jobs
by joshAg 1894 days ago
In C when you have nothing that needs cleanup, it's not the most horrible thing ever:

  int foo(thing_t \*work) {
    int ret = E_SUCCESS;

    if(work->thing == BAD_THING) {
      ret = E_BAD;
      goto exit;
    }
  
    do_some(work);
  
    if(work->thing2 == OTHER_BAD_THING) {
      LOG("whoopsies");
      ret = E_OTHER;
      goto exit;
    }
  
    ret = do_more(work);
    if (!ret) {
      LOG("lazy");
      goto exit;
    }
  
    ret = last_bit_of(work);
  
  exit:
    return ret;
  }
1 comments

I find the safe way to program that is always to set the initial value to some error. You only set it to success at the point you succeed. Then you never have to worry about some odd goto or other break in the control glow being introduced by you or someone else that wasn't paying attention. It's also better self documentation, because then it's obvious at what point you're actually done, in the case your final work isn't aptly named "last_bit_of_work(work)", because you'll see the return variable set to E_SUCCESS immediately afterwards.
agreed, but some people dislike that because you have to have an E_UKNOWN or E_GENERAL or something like that in addition to more specific errors and others dislike it because now there's not something to conveniently store results from called functions in so that they can be checked for errors.