Reputation: 19331
Good day,
I'm reading through some old code I've been asked to maintain, and I see a number of functions that are like so:
uint32_t myFunc(int* pI);
In the case of error conditions within the body of the function, the function exits early by returning a negative errno
value, ie: return (-EINVAL);
Is this value standard (ie: C99, ANSI), C? I've read in the comments that apparently doing this sets the errno
to EINVAL
, but I can't find any documentation to support this. Wouldn't it be better to just declare the function as a signed int (ie: int32_t myFunc(int* pI)
) and treat negative values as error codes, rather than attempt to set errno
in this manner?
Upvotes: 0
Views: 1464
Reputation: 23236
Addressing your question: Is this value standard (ie: C99, ANSI), C?
For C99
"errno which expands to a modifiable lvalue that has type int, the
value of which is set to a positive error number by several library
functions." -- N1256 7.5p2
For POSIX
"The <errno.h> header shall define the following macros which shall
expand to integer constant expressions with type int, distinct
positive values" -- errno.h DSCRIPTION
"Values for errno are now required to be distinct positive values
rather than non-zero values. This change is for alignment with the
ISO/IEC 9899:1999 standard." -- errno.h CHANGE HISTORY Issue 6
A good discussion (and the source of these quotes) is found HERE (search "when to return EINVAL")
Upvotes: 2
Reputation: 215557
Returning a negative value does not set errno
. This is misinformation you picked up (or more likely, which the original author picked up) out-of-context: the mechanism by which the Linux kernel system calls report errors is returning a negative value in the range -4095 to -1, which the userspace code making the syscall then uses (in most cases) to fill in the value of errno
. If you want to set errno
yourself, however, just assign a value to it.
Upvotes: 4