Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why return a negative errno? (e.g. return -EIO)

Another simple example:

if (wpa_s->mlme.ssid_len == 0)     return -EINVAL; 

Why the unary minus? Is this (usually) done for functions that return >0 on success and <(=)0 on failure, or is there some other reason?

like image 664
exscape Avatar asked Dec 04 '09 18:12

exscape


People also ask

Can return code be negative?

Note well that C standard library functions do not return errno codes. When they return a code indicating failure (often, but not always, a negative number), the programmer is obliged to consult the errno variable for a detailed reason -- the function return code generally does not carry that information.

Can Snprintf return negative?

The snprintf function returns an integer value that equals, in magnitude, the number of characters written to the area addressed by dest . If the value returned is negative, then either the maxlen character limit was reached or some other error, such as an invalid format specification, has occurred.

How do I return negative value in CPP?

According to the standard, the return value of main() is passed to std::exit(int) . From there, by C++11 § 18.5, "If status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned.


Video Answer


1 Answers

First, this isn't really a C thing. You're looking at a function that is written in C for some purpose. The same conventions could be used in any language.

Back in my old Unix days, there was something of a convention that 0 meant success, a positive number meant minor problems, and a negative number meant some sort of failure. Therefore, there was also a sort of convention of if (foo() >= 0) { /* success of a sort */ }.

This was doubtless related to Unix process return codes, where 0 was success.

like image 126
David Thornley Avatar answered Sep 22 '22 00:09

David Thornley