Very often I see in C code negation of returned error codes, e.g. return -EINVAL
instead of return EINVAL
. Why used negation?
On many UNIXen, convention for syscalls is that they return the error code negated in case of an error, and the actual value in case of success.
This is translated on the user space side into -1
for errors with the positive error code in errno
, or the actual value in case of success.
The need for this dual-purposing of the return value is because multiple-returns in this kind of language is bothersome, as you’d have to resort to passing in out-parameters to hold an eventual error.
It is a convention; a lot of functions return a stricly positive result on success and a negative result on failure. Initially, it was related to the return code of Unix process. A success was indicated by 0.