James Kuyper
5/3/2011 10:26:00 AM
On 05/03/2011 04:31 AM, pozz wrote:
> A very simple question. What do you use as the return value of a
> function for error/ok results?
> I can't decide between 0 for error and !=0 for ok, or 0 for ok and !=0
> for errors.
>
> If !=0 is ok, I can write:
>
> if (myfunction()) printf("OK\n");
This is a perfectly reasonable approach, but when you use it, one of the
most important things is to make sure to name the function so that it
can be read as a question, and give it a non-zero value if the answer to
that question is "yes". Example from the C standard library: isalpha().
However, there's also lots of functions in the C standard library which
violate this rule; for instance, fseek().
If you can't think of a name for the function which would make this
work, then using this approach is probably not appropriate.
....
> Another strategy is to define custom error code:
>
> #define ERROR_OK 0
> #define ERROR_UNDEFINED 1
> #define ERROR_WRONGVALUE 2
>
> and so on, and always write:
>
> if (myfuction() == ERROR_OK) printf("OK\n");
If your code returns multiple different error codes, then somewhere you
should have a call to the function that actually does different things,
depending upon which error code is returned; a switch() is usually the
best way to do this. You can also have calls that don't make a
distinction; but if there aren't any calls to the function which do make
the distinction, then you don't really need to distinguish different
error conditions.
I'm guilty of violating that rule in my own code; but my intention is
that test drivers for the called routine will check which error code is
returned, even if the actual delivered program does not.
--
James Kuyper