Errors, status, errno, and assertions
Design clear failure outcomes, respect documented errno contracts, keep validation outside assert, and recognize nonlocal-jump limits.
In this chapter8 sections
Failure can be part of a valid operation: input may be invalid, a file may be missing, or storage may be unavailable. Interfaces report these cases in different ways. We will separate returned status, error information, and assertions about program assumptions.
1. Learn each operation’s convention
| Operation | Interpretation |
|---|---|
| fopen | Non-null stream / null failure |
| fgetc | Character result / EOF; inspect indicators to distinguish end and error |
| fread | Complete elements transferred; interpret a short count |
| printf | Nonnegative character count / negative failure |
| fseek | Zero success / nonzero failure |
| fclose | Zero success / EOF failure; stream is disassociated either way |
| Custom interface | A documented status and a separate result, if useful |
Do not invent one “all negative values are errors” rule for every API. An integer result can legitimately be negative, a successful C function may return nonzero, and a zero count may mean an empty request. Follow the operation’s contract before deciding to retry, stop normally, report a diagnostic, or reject a record.
2. Keep status separate from useful data
#include <assert.h>
#include <limits.h>
#include <stddef.h>
enum DivideStatus { DIVIDE_OK, DIVIDE_NO_RESULT, DIVIDE_BY_ZERO, DIVIDE_RANGE } ;
static enum DivideStatus divide_int(int left, int right, int *result)
{
if (result == NULL) return DIVIDE_NO_RESULT;
if (right == 0) return DIVIDE_BY_ZERO;
if (left == INT_MIN && right == -1 && INT_MIN < -INT_MAX) return DIVIDE_RANGE;
*result = left / right;
return DIVIDE_OK;
}
int main(void)
{
int value = 99;
enum DivideStatus bad = divide_int(12, 0, &value);
assert(bad == DIVIDE_BY_ZERO && value == 99);
enum DivideStatus good = divide_int(12, 3, &value);
assert(good == DIVIDE_OK && value == 4);
enum DivideStatus no_result = divide_int(1, 1, NULL);
assert(no_result == DIVIDE_NO_RESULT);
enum DivideStatus edge = divide_int(INT_MIN, -1, &value);
assert(edge == (INT_MIN < -INT_MAX ? DIVIDE_RANGE : DIVIDE_OK));
return 0;
}
A quotient of zero is valid data, so it should not also ambiguously mean failure. This helper returns a named status and writes the result only on success. The range guard accounts for C17’s permitted signed representations: INT_MIN divided by -1 is unrepresentable when the negative range has an extra value. The null destination and zero divisor are rejected before any invalid operation occurs. Callers choose how to present the failure.
3. errno is documented context, not automatic truth
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
const char *text = "12";
char *end = NULL;
errno = 0;
long value = strtol(text, &end, 10);
int conversion_error = errno;
if (end == text || *end != '\0' || conversion_error == ERANGE) return EXIT_FAILURE;
if (printf("value=%ld\n", value) < 0) return EXIT_FAILURE;
return fflush(stdout) == EOF ? EXIT_FAILURE : EXIT_SUCCESS;
}
errno is a macro from <errno.h> designating a modifiable int lvalue with thread-local storage duration in C11/C17. A successful unrelated call need not clear an old value. Set it to zero before an operation such as strtol when the documented checks require that, then capture the relevant value before another library call can change it.
In ISO C, not every stdio failure is required to set errno. A bare perror("read") after an arbitrary failure can therefore describe stale information unless the chosen operation/platform supplies an errno contract. perror describes the current errno; strerror describes the error number passed to it. Error-message wording is implementation-dependent and must not be parsed as a stable machine protocol.
4. Assertions check expectations, not untrusted input
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
if (argc != 2 || strcmp(argv[1], "read") != 0) return EXIT_FAILURE;
const char *mode = argv[1];
assert(strcmp(mode, "read") == 0);
if (printf("mode=%s\n", mode) < 0) return EXIT_FAILURE;
return fflush(stdout) == EOF ? EXIT_FAILURE : EXIT_SUCCESS;
}
The external mode check is ordinary control flow and stays present with NDEBUG defined. The assertion documents a later internal expectation. Never put a required read, write, close, assignment, or validation solely inside assert: disabling assertions can remove that expression completely. Assert failure terminates abnormally; it is not a recovery path for a mistyped filename. The example is checked with assertions both enabled and disabled.
5. Nonlocal jumps are an advanced control-flow contract
setjmp/longjmp can transfer control back to a saved environment without returning normally through intervening calls. They do not automatically release files or allocations. The saved function invocation must remain active in the same thread, and leaving the relevant enclosing variably-modified scope can also invalidate the jump. Changed non-volatile automatic locals in the setjmp function can become indeterminate after longjmp.
The invocation itself has restricted expression contexts. if (setjmp(env) == 0) is valid; int status = setjmp(env); is not a permitted context and has undefined behavior. These rules are independent of whether a small test seems to work. Prefer ordinary status returns and explicit cleanup for the input flows in this unit.
Inspect a valid saved-jump context
#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>
static jmp_buf checkpoint;
static void jump_back(void)
{
longjmp(checkpoint, 1);
}
int main(void)
{
if (setjmp(checkpoint) == 0) {
jump_back();
} else {
if (puts("returned to checkpoint") == EOF) return EXIT_FAILURE;
}
return fflush(stdout) == EOF ? EXIT_FAILURE : EXIT_SUCCESS;
}
Primary references and further reading
- WG14 N1570 — public C11 committee draft: 6.5.5p5–p6, 7.2, 7.5, 7.13, 7.21.10, 7.24.6.2. Stable core provisions used for the C17 baseline; not the final ISO publication.
Before you move on
- Interfaces report failure through their documented status and result conventions.
- errno is meaningful only under the applicable operation’s error rules.
- Assertions express program assumptions and cannot replace validation that must run in every build.
Keep these ideas separate
- Assertion / Input validation
- An assertion can be disabled; required checks on untrusted data must remain part of the program’s behavior.
Why is a nonzero errno after an unrelated successful operation insufficient evidence of a new failure?
Optional: say it aloud or keep a note. You can continue whenever you are ready.Check your understanding
Optional. Answers are not saved or sent, and reading stays unrestricted.
Read the explanation for every choice
- Yes, every successful function resets errno.
Successful functions do not generally promise to clear errno.
- Yes, errno replaces every function’s return value.
Each interface defines its own error indication and when errno is meaningful.
- No. Follow that function’s documented failure indication and errno rules.
✓ Correct reasoning. The value can be left over from an earlier operation.
C17
Quick reference from the earlier edition
Retained for existing section links and saved passages. The expanded lessons above explain the connected ideas; exact corrections are recorded in the source review.
C has no exceptions, so error handling relies on conventions layered on top of ordinary return values:
- Return-value conventions. Many standard functions signal failure through a distinctive return value —
NULLformalloc,-1for many POSIX calls,EOFforgetchar— which places the burden on the caller to check every call that can fail. - errno.
<errno.h>defines a macro expanding to a modifiableintlvalue with thread-local storage in C11/C17, not necessarily an ordinary global variable. Check the function's documented return/error convention first: a successful call need not clear an olderrnovalue. For functions such asstrtol, seterrno = 0before the call when its documented checks require it.perrorandstrerrordescribe an error number; not every library failure is required to seterrno. - assert.
<assert.h>'sassert(condition)aborts the program with a diagnostic message ifconditionis false, intended for catching programmer errors during development. DefiningNDEBUGbefore including<assert.h>strips all assertions from the build, soassertshould never guard a check a release build actually depends on. - setjmp/longjmp.
longjmpcan return to a matchingsetjmponly while that function invocation is still active and in the same thread; jumping back into a function that has returned is undefined behavior. Non-volatile automatic locals in thesetjmpfunction that changed aftersetjmphave indeterminate values afterlongjmp. No automatic resource cleanup is performed.setjmpalso has restricted call contexts:if (setjmp(env) == 0)is valid, butint status = setjmp(env);has undefined behavior. These facilities are not ordinary exceptions.
Ready for the next idea?
Mark this chapter as read whenever you feel ready.