Should I set errno? Should I set errno? c c

Should I set errno?


This is a bit old, but errno - manual section 3 says that you can directly assign to it, even though it is a macro, and it will be thread local


Not only can you set errno, in many cases you should set errno. When calling some library functions you can only reliably detect an error if you first set errno to zero. See strtol for an example.

From the POSIX specification of strtol:

[CX] [Option Start] The strtol() function shall not change the setting of errno if successful.

Since 0, {LONG_MIN} or {LLONG_MIN}, and {LONG_MAX} or {LLONG_MAX} are returned on error and are also valid returns on success, an application wishing to check for error situations should set errno to 0, then call strtol() or strtoll(), then check errno. [Option End]


Actually, you probably can do "proper" (as you put it) error management since you return an int.

Just use non-negative values for the number of bytes read or written and negative values for error codes. You don't have to limit yourself to -1:

enum myerrors {    ERR_NO_MEMORY    = -1,    ERR_BAD_ARGS     = -2,    ERR_CPU_EXPLODED = -3,    // and so on};

However, setting errno in the fashion you want is valid. The standard states that errno expands to a modifiable lvalue, meaning you can set it. From C1x/n1425, 7.5 Errors <errno.h>:

... and 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.