errno
- C course
- Intermediate
- Lesson 53/116
- 4 min
Learn error codes with errno.
The errno global
C tracks failures with the errno global variable. You must include <errno.h>. errno holds an error code; successful calls don't reset it, so errno = 0; before a call is a good habit.
Example: if fopen returns NULL, errno tells you why. Values are constants like EINVAL, ERANGE, ENOENT. errno isn't an int but an expandable macro, so you can take its address with &errno.
Common errno constants
errno's values are standard constants. EINVAL means invalid argument, ERANGE result out of range, ENOENT no such file, ENOMEM out of memory.
You test these with if (errno == EINVAL). The numeric values vary by platform, so always compare by name. strerror and perror convert these codes to human-readable text; we'll see them in the next lesson.
Practice Read and print errno
Include <errno.h> and <stdio.h>. In main, reset with errno = 0;, assign strtol("xyz", NULL, 10); to long v, then print errno with printf("%d\n", errno);. strtol doesn't change errno here; the goal is to show reading errno.
Starter code
#include <stdio.h>
// Include errno.h
int main(void) {
// Reset errno
// Convert "xyz" with strtol
// Print errno
return 0;
}Sample solution
#include <stdio.h>
#include <errno.h>
int main(void) {
errno = 0;
long v = strtol("xyz", NULL, 10);
printf("%d\n", errno);
return 0;
}Expected output
0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How do you reset errno?
errno = 0;
result = strtol("abc", NULL, 10);- errno resets automatically
- Set errno = 0; after the call
- Set errno = 0; before the call Correct answer
- errno never needs reset
Explanation: Successful calls don't clear errno; you reset it manually before the call.
2 Reset errno before the call
errno = ____;
long v = strtol("abc", NULL, 10);
errno = 0;
long v = strtol("abc", NULL, 10);
Explanation: errno = 0; clears any old value.
3 Match errno constants to their meaning
| Term | Meaning |
|---|---|
EINVAL |
Invalid argument |
ERANGE |
Result out of range |
ENOENT |
No such file |
ENOMEM |
Out of memory |