<errno.h> declares errno—a modifiable int lvalue that library functions set when they fail. It also defines codes like EDOM and ERANGE. Use it to learn why a call failed after you check the return value.
Remember
#include <errno.h>
1. check return value (NULL, -1, …)
2. then read errno
errno = 0; // reset before calls like strtol
success does NOT clear errno
perror("msg") → stderr (<stdio.h>)
strerror(errno) → string (<string.h>)
Return value first, then errno. Reset when the function can succeed with a leftover error code.
Include <errno.h> (plus stdio.h / string.h for helpers).
Call the library function and check its return value.
If it failed, read errno (or print with perror / strerror).
For strtol-style APIs, set errno = 0 immediately before the call.
Piece
Required?
Role
#include <errno.h>
Yes
Provides errno, EDOM, ERANGE
Return check
Yes
Decide if the call failed
errno = 0
Sometimes
Needed before strtol / ambiguous returns
Pseudocode
Pseudocode
errno = 0 // when the API needs a clean slate
result = library_call(...)
if result indicates failure: // NULL, -1, end==start, …
code = errno
if code == EDOM: domain error
if code == ERANGE: range / overflow
report with perror or strerror(code)
else:
// success — do not trust an old errno value
Reference
Cheat Sheet
Keep these symbols handy while handling library errors.
Symbol
Meaning
errno
Last error code (macro → int lvalue)
EDOM
Domain error (invalid math input)
ERANGE
Range error (overflow / underflow)
perror("msg")
Print prefix + error text to stderr
strerror(errno)
Error text as a string
Safe pattern
Check return → then read errno
Reset pattern
errno = 0 before strtol
Try it
Live Preview
Pick a failure scenario and see the typical return value, errno code, and message pattern (simulated).
Browser simulation of common errno patterns (same idea as the C examples below).
Result
fopen("missing.txt", "r")
→ returns NULL (failure)
→ errno ≈ ENOENT (e.g. 2)
→ strerror: No such file or directory
Pattern: if (fp == NULL) use errno
Call:
fp = fopen("nonexistent.txt", "r")
fp == NULL? → yes (failure)
errno → set (often ENOENT / 2 on Linux)
strerror → "No such file or directory"
Correct order:
1. see NULL
2. then read errno / strerror
Wrong order:
read errno first without checking return
→ may show an old, unrelated error
Code
C Examples
Compile with gcc file.c -std=c11 -o out. Add -lm for the sqrt example.
Example 1 — Open a Missing File with strerror
fopen returns NULL on failure and sets errno. Check the pointer first.
sqrt(-1) = nan
sqrt domain error: Numerical argument out of domain
How It Works
Clear errno. So a leftover code cannot look like a new failure.
Call sqrt(-1). The result is typically NaN; the function also sets errno to EDOM.
Compare to EDOM. That confirms a domain error from math.h.
Report with perror. Prefix plus system message go to stderr—handy while debugging.
Example 3 — Detect Overflow with strtol and ERANGE
strtol returns a number even on overflow. You must reset errno and check it (see stdlib.h).
C
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
const char *big = "999999999999999999999";
char *end = NULL;
long value;
errno = 0;
value = strtol(big, &end, 10);
if (errno == ERANGE) {
printf("Overflow: value out of long range\n");
} else if (end == big) {
printf("No digits parsed\n");
} else {
printf("Parsed: %ld\n", value);
}
return 0;
}
Output
Overflow: value out of long range
How It Works
Reset first. Without errno = 0, a stale code could look like overflow.
Parse the huge string.strtol cannot fit it in a long.
See ERANGE. That is the range / overflow signal from errno.h.
Also check end. If nothing was converted, end == big—a different kind of failure.
Edge Cases & Pitfalls
These mistakes cause false alarms or missed failures.
order
Return value before errno
Never trust errno alone. Successful calls often leave the old value unchanged.
reset
Reset for ambiguous APIs
strtol and friends need errno = 0 right before the call.
coverage
Not every function sets errno
Only documented failures set it. Always start from the man page / return value.
assert
Not a substitute for assert
Use assert for programmer bugs; use errno for recoverable library/OS errors.
Analysis
Performance Notes
Approach
Cost
Best for
Read errno after failure
Negligible
Normal error paths
perror / strerror
String lookup + I/O
Logging and diagnostics
Checking errno on every success
Wasted / misleading
Avoid—check returns first
Error reporting is cheap compared with the failed I/O or parse itself. Keep the happy path free of unnecessary errno tests.
Remember
Key Takeaways
Role: explain why a library call failed.
Order: check return value, then read errno.
Reset:errno = 0 before strtol-style calls.
Report:perror for stderr; strerror for custom text.
One line:errno answers “why did this library call fail?”—only after the return value says it failed.
Frequently Asked Questions
errno.h declares the errno macro—a modifiable int lvalue that library functions set when they fail. It also defines error code macros like EDOM and ERANGE. Include it with #include <errno.h> whenever you inspect or reset errno.
errno is a macro that expands to an lvalue (often thread-local since C11). You do not declare extern int errno yourself in portable code; just #include <errno.h> and use errno directly.
Set errno = 0 immediately before a call when you need to know whether that specific call failed—especially for functions like strtol() that return a value on both success and failure. Many functions only set errno on error and leave it unchanged on success.
perror(msg) prints your message plus a system error string for the current errno to stderr. strerror(errno) returns a pointer to a human-readable string you can pass to printf. perror needs <stdio.h>; strerror needs <string.h>.
No. Always check the function's return value first (NULL, -1, EOF, etc.). Only some functions document that they set errno on failure—fopen, strtol, and many math functions do; others may not touch errno at all.
EDOM means a domain error (invalid input to a math function, e.g. sqrt(-1)). ERANGE means a range error (result too large, e.g. overflow in strtol). Both are macros defined in errno.h with positive integer values.