Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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

share|improve this question

2 Answers 2

up vote 5 down vote accepted

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.

share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.