Resetting errno before library calls
What you'll learn: Why you must manually clear the global error flag to avoid misinterpreting successful function calls as failures.
The Sticky Sticky Note
Imagine you have a single sticky note on your desk. Every time a coworker runs into a problem, they write "ERROR" on it and leave it there. If a coworker completes a task successfully, however, they don't erase the note; they just walk away.
If you look at the note and see "ERROR," you don't actually know if the current task failed or if you are looking at a leftover message from three hours ago.
In C, the errno variable is that sticky note. Many functions in the Standard Library set errno to a non-zero value when they fail. Crucially, almost no functions reset it to 0 when they succeed.
The False Positive Trap
If you call a function that fails, errno is updated. If you then call a second function that succeeds, errno will still hold the error code from the first failure. If you check errno after the second call without clearing it first, your program will think the second call failed, leading to a "false positive" error report.
To use errno reliably, you must manually reset it to 0 immediately before the function call you want to monitor.
Putting it into Practice
To use this pattern, include <errno.h>. Before calling a library function (like strtol or sqrt), wipe the slate clean.
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
int main() {
const char *text = "42";
char *endptr;
// 1. Reset errno to 0 before the call
errno = 0;
long value = strtol(text, &endptr, 10);
// 2. Check if errno was changed by the function
if (errno != 0) {
perror("Conversion error");
} else {
printf("Converted value: %ld\n", value);
}
return 0;
}
By setting errno = 0 right before strtol, you guarantee that if errno is non-zero afterward, it was definitely caused by that specific line of code. This practice is essential for functions that return values which could technically be valid numbers (like -1 or 0), making errno the only way to distinguish a real result from a failure.
Key takeaway
Always set errno = 0 immediately before a library call so you don't accidentally react to an old error from a previous operation.