errno is a C standard library macro identifying a thread-local integer error indicator. Library functions may use it to record a specific failure condition, usually alongside a return value that signals failure. Check that return value first; inspect errno only when the function's documented error strategy makes it relevant. section 8.1.3
Pair a failure return with a diagnostic
if (puts("hello world") == EOF) { perror("can't output to terminal:"); exit(EXIT_FAILURE); } Here, puts reports failure through EOF, while perror uses the current error state to provide a more specific diagnostic. If recovery is possible, reset the error state after handling the failure so later checks are not confused. section 8.1.3
Detect numeric conversion range errors
A strtoul implementation returns ULONG_MAX and sets errno to ERANGE when the input number is too large for unsigned long. A wrapper can also set errno to EINVAL when its base argument exceeds 36: if (base > 36u) { errno = EINVAL; return ULONG_MAX; } section 8.4
Use errno as part of a wider error-checking discipline:
- Check each library function's documented return value for failure. section 8.1.3
- Use perror when the failure state should become a human-readable diagnostic. section 8.1.3
- Reset errno after recoverable failure handling when continued execution depends on an unambiguous error state. section 8.1.3
Table 8.2. Error return strategies for C library functions Some functions may also indicate a specific error condition through the value of the errno macro. (view table figure)
| Failure return |
Test |
Typical case |
Example |
|---|---|---|---|
| 0 | !value | Other values are valid | fopen |
| Special error code | value == code | Other values are valid | puts, clock, mktime, strtod, fclose |
| Nonzero value | value | Value otherwise unneeded | fgetpos, fsetpos |
| Special success code | value != code | Case distinction for failure condition | thrd_create |
| Negative value | value < 0 | Positive value is a counter | printf |
Compare the library functions' failure return conventions and see where errno may provide an additional specific condition. section 8.1.3


