YOUR C LEARNING COMPANION

Find your next idea.

Learning path
Working with inputChapter 55 of 73

Errors, status, errno, and assertions

Design clear failure outcomes, respect documented errno contracts, keep validation outside assert, and recognize nonlocal-jump limits.

6 min readIntermediateC17 baseline
Offline reading
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

OperationInterpretation
fopenNon-null stream / null failure
fgetcCharacter result / EOF; inspect indicators to distinguish end and error
freadComplete elements transferred; interpret a short count
printfNonnegative character count / negative failure
fseekZero success / nonzero failure
fcloseZero success / EOF failure; stream is disassociated either way
Custom interfaceA 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

Complete C17 program
#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

Complete C17 program
#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

Complete C17 program
#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
Complete C17 program
#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

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.
Explain it in your own words

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.

Does a nonzero errno alone prove the last function call failed?
Read the explanation for every choice
  1. Yes, every successful function resets errno.

    Successful functions do not generally promise to clear errno.

  2. Yes, errno replaces every function’s return value.

    Each interface defines its own error indication and when errno is meaningful.

  3. 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 — NULL for malloc, -1 for many POSIX calls, EOF for getchar — which places the burden on the caller to check every call that can fail.
  • errno. <errno.h> defines a macro expanding to a modifiable int lvalue 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 old errno value. For functions such as strtol, set errno = 0 before the call when its documented checks require it. perror and strerror describe an error number; not every library failure is required to set errno.
  • assert. <assert.h>'s assert(condition) aborts the program with a diagnostic message if condition is false, intended for catching programmer errors during development. Defining NDEBUG before including <assert.h> strips all assertions from the build, so assert should never guard a check a release build actually depends on.
  • setjmp/longjmp. longjmp can return to a matching setjmp only 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 the setjmp function that changed after setjmp have indeterminate values after longjmp. No automatic resource cleanup is performed. setjmp also has restricted call contexts: if (setjmp(env) == 0) is valid, but int 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.

CHAPTER 55 / 73

In this chapter

Errors, status, errno, and assertions

Search all 73 chapters in both languages.EN + HG

Try “pointer”, “why int”, or “undefined behavior”.

Concepts connect. Follow your curiosity.↑ ↓ to explore · Enter to open
MAKE YOURSELF COMFORTABLE

Your reading space

Appearance

A clear canvas with balanced contrast.

Text size

100%
AA

Reading tools

Your data stays in this browser

Export a backup before changing browsers or replacing an older version of the reader.

YOUR PERSONAL MARGINS

My notebook

Saved on this device
A LITTLE CLARITY

The glossary

A starting meaning, then a chapter to go deeper.

A QUICK DEFINITION

A little clarity

Read the full explanation →

A thought worth keeping