13

Very often I see in C code negation of returned error codes, e.g. return -EINVAL instead of return EINVAL. Why used negation?

2 Answers 2

10

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.

4

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.