santosh said:
... snip ...
As an aside, is there an explanation why certain function in the
standard library return 0 to indicate success while certain others
return 1 for the same?
Off-hand, I can't think of any C standard library functions that return 0 to
mean "success", but no doubt you have an example in mind. Having said that,
I generally use 0 for that purpose, which leaves all the other possible int
values for documenting the exact error that occurred. When I make an
exception, it is for pointer-returning functions, where clearly NULL is the
only value I can reasonably choose to mean "oopsie" (e.g. "couldn't
allocate this resource").
Is it a historical/legacy issue or is there a
method behind the apparent inconsistency?
Actually, the consistency is pretty good! But different kinds of function
have different purposes, so the consistency is within function groups,
rather than across the board. This is not unreasonable.
Functions that determine a truth/falsehood - is* - return 0 for false and
non-zero for true.
Functions that determine a relationship - *cmp, and our own int(*)(const
void *, const void *) - return < 0 for less, 0 for equal, and > 0 for
greater.
Functions that yield a count - fread, fwrite, strlen, strspn, strcspn -
return 0 for a 0 count, > 0 for a non-zero count.
Functions that yield a pointer - fgets, malloc, strstr, strtok - return a
valid pointer if they can, or NULL if they can't.
Functions that yield the result of a calculation - sin, cos, tan, strtol,
strtod - tend to report errors via some other mechanism than their return
value (e.g. domain errors, endptr, whatever).
Functions that retrieve or process a single character - getc, fgetc,
getchar, to* - yield EOF on error.
I do not claim that the consistency within groups is 100%, but off the top
of my head I can't think of any counter-examples within the categories I've
listed.