C errno.h Header

Beginner
6 min read
Updated: Oct 2026
3 examples
Live preview

What Is errno.h?

<errno.h> declares errno—a modifiable int lvalue that library functions set when they fail. It also defines codes like EDOM and ERANGE. Use it to learn why a call failed after you check the return value.

Remember
#include <errno.h>

1. check return value (NULL, -1, …)
2. then read errno

errno = 0;   // reset before calls like strtol
success does NOT clear errno

perror("msg")      → stderr  (<stdio.h>)
strerror(errno)    → string  (<string.h>)
UsePrefer
Why a library call failederrno after a failed return
Quick message to stderrperror (stdio.h)
Format your own messagestrerror (string.h)

How to Use errno in C

Return value first, then errno. Reset when the function can succeed with a leftover error code.

  1. Include <errno.h> (plus stdio.h / string.h for helpers).
  2. Call the library function and check its return value.
  3. If it failed, read errno (or print with perror / strerror).
  4. For strtol-style APIs, set errno = 0 immediately before the call.
PieceRequired?Role
#include <errno.h>YesProvides errno, EDOM, ERANGE
Return checkYesDecide if the call failed
errno = 0SometimesNeeded before strtol / ambiguous returns

Pseudocode

Pseudocode
errno = 0                    // when the API needs a clean slate
result = library_call(...)

if result indicates failure:   // NULL, -1, end==start, …
    code = errno
    if code == EDOM:   domain error
    if code == ERANGE: range / overflow
    report with perror or strerror(code)
else:
    // success — do not trust an old errno value

Cheat Sheet

Keep these symbols handy while handling library errors.

SymbolMeaning
errnoLast error code (macro → int lvalue)
EDOMDomain error (invalid math input)
ERANGERange error (overflow / underflow)
perror("msg")Print prefix + error text to stderr
strerror(errno)Error text as a string
Safe patternCheck return → then read errno
Reset patternerrno = 0 before strtol

Live Preview

Pick a failure scenario and see the typical return value, errno code, and message pattern (simulated).

Browser simulation of common errno patterns (same idea as the C examples below).

Result
fopen("missing.txt", "r")
→ returns NULL (failure)
→ errno ≈ ENOENT (e.g. 2)
→ strerror: No such file or directory

Pattern: if (fp == NULL) use errno

Worked Walkthrough — Missing File

Trace fopen when the file does not exist.

Calculation
Call:
  fp = fopen("nonexistent.txt", "r")

fp == NULL?  → yes (failure)
errno        → set (often ENOENT / 2 on Linux)
strerror     → "No such file or directory"

Correct order:
  1. see NULL
  2. then read errno / strerror

Wrong order:
  read errno first without checking return
  → may show an old, unrelated error

C Examples

Compile with gcc file.c -std=c11 -o out. Add -lm for the sqrt example.

Example 1 — Open a Missing File with strerror

fopen returns NULL on failure and sets errno. Check the pointer first.

C
#include <errno.h>
#include <stdio.h>
#include <string.h>

int main(void) {
    FILE *file = fopen("nonexistent.txt", "r");

    if (file == NULL) {
        printf("Error opening file: %s (errno=%d)\n",
               strerror(errno), errno);
    } else {
        fclose(file);
    }

    return 0;
}

How It Works

  1. Try to open. fopen looks for a file that is not there.
  2. Check NULL. Failure is reported by the return value, not by peeking at errno alone.
  3. Read errno. The library stored a positive code (often ENOENT / 2).
  4. Print with strerror. You get a readable phrase for logs or UI text via string.h.

Example 2 — Math Domain Error with perror

sqrt(-1) is invalid input. Reset errno, call sqrt, then check EDOM.

C
#include <errno.h>
#include <math.h>
#include <stdio.h>

int main(void) {
    errno = 0;
    double result = sqrt(-1.0);

    printf("sqrt(-1) = %g\n", result);

    if (errno == EDOM) {
        perror("sqrt domain error");
    }

    return 0;
}

How It Works

  1. Clear errno. So a leftover code cannot look like a new failure.
  2. Call sqrt(-1). The result is typically NaN; the function also sets errno to EDOM.
  3. Compare to EDOM. That confirms a domain error from math.h.
  4. Report with perror. Prefix plus system message go to stderr—handy while debugging.

Example 3 — Detect Overflow with strtol and ERANGE

strtol returns a number even on overflow. You must reset errno and check it (see stdlib.h).

C
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    const char *big = "999999999999999999999";
    char *end = NULL;
    long value;

    errno = 0;
    value = strtol(big, &end, 10);

    if (errno == ERANGE) {
        printf("Overflow: value out of long range\n");
    } else if (end == big) {
        printf("No digits parsed\n");
    } else {
        printf("Parsed: %ld\n", value);
    }

    return 0;
}

How It Works

  1. Reset first. Without errno = 0, a stale code could look like overflow.
  2. Parse the huge string. strtol cannot fit it in a long.
  3. See ERANGE. That is the range / overflow signal from errno.h.
  4. Also check end. If nothing was converted, end == big—a different kind of failure.

Edge Cases & Pitfalls

These mistakes cause false alarms or missed failures.

order

Return value before errno

Never trust errno alone. Successful calls often leave the old value unchanged.

reset

Reset for ambiguous APIs

strtol and friends need errno = 0 right before the call.

coverage

Not every function sets errno

Only documented failures set it. Always start from the man page / return value.

assert

Not a substitute for assert

Use assert for programmer bugs; use errno for recoverable library/OS errors.

Performance Notes

ApproachCostBest for
Read errno after failureNegligibleNormal error paths
perror / strerrorString lookup + I/OLogging and diagnostics
Checking errno on every successWasted / misleadingAvoid—check returns first

Error reporting is cheap compared with the failed I/O or parse itself. Keep the happy path free of unnecessary errno tests.

Key Takeaways

  • Role: explain why a library call failed.
  • Order: check return value, then read errno.
  • Reset: errno = 0 before strtol-style calls.
  • Report: perror for stderr; strerror for custom text.

One line: errno answers “why did this library call fail?”—only after the return value says it failed.

Frequently Asked Questions

errno.h declares the errno macro—a modifiable int lvalue that library functions set when they fail. It also defines error code macros like EDOM and ERANGE. Include it with #include <errno.h> whenever you inspect or reset errno.
errno is a macro that expands to an lvalue (often thread-local since C11). You do not declare extern int errno yourself in portable code; just #include <errno.h> and use errno directly.
Set errno = 0 immediately before a call when you need to know whether that specific call failed—especially for functions like strtol() that return a value on both success and failure. Many functions only set errno on error and leave it unchanged on success.
perror(msg) prints your message plus a system error string for the current errno to stderr. strerror(errno) returns a pointer to a human-readable string you can pass to printf. perror needs <stdio.h>; strerror needs <string.h>.
No. Always check the function's return value first (NULL, -1, EOF, etc.). Only some functions document that they set errno on failure—fopen, strtol, and many math functions do; others may not touch errno at all.
EDOM means a domain error (invalid input to a math function, e.g. sqrt(-1)). ERANGE means a range error (result too large, e.g. overflow in strtol). Both are macros defined in errno.h with positive integer values.

Next: float.h

Explore floating-point limits and precision macros.

float.h tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful