Search code examples
cmacrosreturnstatus

What should be the initial value for return status in C?


Error handling code for any general function follows this template Two questions from my end--

  1. What should be the default FAILURE value? (1 to keep up with the main or 0, or -1 to avoid all the confusion)
  2. What should be the initial value of status? (FAIL or PASS)

Code:

#define FAILURE 0  //or shall it be 1 for success and 0 for failure
#define SUCCESS 1

int DoSomething() {
    int status = FAILURE;  //or shall we assign success by default?

    if (error1)
        return FAIL_A
    if (error2)
        return FAIL_B

    return SUCCESS;
}

int GetItDone() {
   status = FAIL;

   Status = DoSomething();
   if (PASS != status) //likewise many calls can happen later
     goto END;

END:
  return status;
    }

The status bubble up through function calls.


Solution

  • The convention is 0 for success, negative values for various failures, and positive values for predicated successes.

    Of these, returning 0 for success is the most frequently observed: doing otherwise would be idiosyncratic.

    As for your code, setting the status to a failure code initially and changing it to success as appropriate will afford more program stability.