C Programming • C17 baseline, standards-specific features labeled
Error Handling with Return Values and errno
Make failure observable through return values, status codes, and documented error channels.
C does not impose one universal error mechanism. Functions may return a status, a sentinel value, or set errno. Check the mechanism documented by the function, preserve useful context, and do not assume errno is meaningful after a successful call.
Example
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
int parse_count(const char *text, long *count) {
if (text == NULL || count == NULL) {
return 0;
}
char *end = NULL;
errno = 0;
long value = strtol(text, &end, 10);
if (text == end || errno == ERANGE || *end != '\0') {
return 0;
}
*count = value;
return 1;
}
What to expect
The function returns zero for invalid or out-of-range text and writes the parsed value only on success.
Key idea: Document whether output parameters are changed on failure and check every operation that can fail.