I have a function which should tell me if a resource exists. Should this function return 0 on exist, 1 on not-exist and -1 on an error or should it return 0 on exist and -1 on not existent /error?
If the function is designed as a boolean, as indicated by a name such as
is_file_present(), it should return 1 when the resource is present, so that it can be used in tests, such as:
if (is_file_present(...)) ... open file ... if (!is_file_present(...)) ... print an error ...
On the other hand, if the function's real purpose are its side effects, and its result serve to indicate their success, it is acceptable to return 0 for the no-error case and an error code, such as -1, when there is an error. For example:
if (create_resource(...) == 0) ... resource has been created ... else ... handle error ...
The use of -1 for error codes allows to use the same error convention for functions that return a count of items or an index.
If your compiler is not archaic and you can use the C99 standard, you could use the header
stdbool.h and return
true if the resource exist and
false if the resource doesn't exist. That's a lot cleaner IMHO.
Like other people said it is about style. You can prefer to return 0 on non-existent and 1 on exists. Also for errors you can add an error or exception pointer pointer (** double stars)parameter to your function signature to indicate a failure. It can be a simple boolean or integer or a struct that contains detailed info about failure. Like an error code and message. This pattern occurs a lot in objective-c frameworks. Also AFAIK there is no exception stack in c so this approach may be the cleanest way to do it. I'd like to write some example code but i'm on mobile. I hope this helps.