I have a function that may or may not set errno because it is implementation-defined, and I just want to print errno if it exists, and not if it doesn't. I tried to figure out if I can test if errno == 0, but people say not to do that, so now I had the idea to just use perror regardless if errno is set or not. I do include errno.h, but I hope stdio.h also includes it since it has perror().
Asked
Active
Viewed 161 times
-1
-
How does your function report an error? – Stephen Newell Oct 12 '22 at 15:45
-
6Normally you first check if a function returns an error. Then you check `errno` to see which error it is. – Gerhardh Oct 12 '22 at 15:49
-
Don't use `perror` without an error, be aware that some functions sets `errno` not only to return an error but as a mechanism to indicate that the user should take some action, for example with the POSIX functions `read` and `write` you check for `errno == EAGAIN` when performing non-blocking I/O, It means: "there is no data available right now, try again later", this value is kept in the variable until it is not replaced by another error, so you could be printing errors not related to a specific problem. – David Ranieri Oct 12 '22 at 16:04
-
[As per Gerhardh], normally you check the return value of a function for error. (e.g.) `stat` will return -1 if there's an error. This is typical. But, some functions can't return an error because _all_ return values are valid (e.g.) `strtol`. The convention for most functions is to _not_ set/change `errno` if the function does _not_ generate an error. So, the usual remedy for functions that can't return an error value is for the caller to set `errno` to 0 before the call. Then, check `errno != 0` after the call. See: https://man7.org/linux/man-pages/man3/strtol.3.html – Craig Estey Oct 12 '22 at 16:07
1 Answers
0
According to the C Standard (7.21.10.4 The perror function)
2 The perror function maps the error number in the integer expression errno to an error message. It writes a sequence of characters to the standard error stream thus: first (if s is not a null pointer and the character pointed to by s is not the null character), the string pointed to by s followed by a colon (:) and a space; then an appropriate error message string followed by a new-line character. The contents of the error message strings are the same as those returned by the strerror function with argument errno.
So if errno
is not set there is no sense to call perror
.

Vlad from Moscow
- 301,070
- 26
- 186
- 335
-
1There is also no sense to even check `errno` if the function one is expecting to possibly fail is not failing. But if it is failing, checking `errno` is "set" is not something that is usually done as well. – Eugene Sh. Oct 12 '22 at 15:51