views:

302

answers:

3

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?

+1  A: 

That's basically the reasons. Lots of functions have lots of "good" positive results, so that leaves the negative values for error codes.

C / POSIX error codes are a bit "historically grown," so there's not much sense in trying to attribute too much rhyme or reason to them.

Many more modern languages throw exceptions for errors so that they don't have to hijack part of their possible response range for error codes. Of course there are trade-offs either way.

Carl Smotricz
There at least used to be a tendency to define 0 as success, positive as successful with problems, and negative as unsuccessful - at least in my old Unix days.
David Thornley
A: 

Your understanding is correct. The obvious interpretation is the right one.

I believe this might be classified as the sentinel pattern and I suppose you could call it a "sentinel return". It's actually a combination of a sentinel "value" and an error code, and it's easier to type and easier to make thread-safe than returning an error code in one place and a sentinel value for error in another.

Wikipedia reports that a sentinel value is used to terminate a loop, but I would think that a function return would be a far more common instance. I guess no one is precisely in charge of these definitions.

DigitalRoss
A: 

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.

David Thornley