Course contentsShow
← C
Lesson 903 of 1,21912. The Standard LibraryFree lesson

When to use `errno` vs return codes

When to use errno vs return codes

What you'll learn: How to decide between checking a function's direct return value and inspecting the global error flag for precise debugging.

The Two Signals

In C, functions usually communicate failure in two stages. Imagine a waiter at a restaurant. If they come back and say, "We can't make that dish," that is a return code. If you then ask, "Why? Are you out of ingredients or is the stove broken?" and they check a shared logbook in the kitchen, that is errno.

Most Standard Library functions use a simple return value (like -1 or NULL) to signal that something went wrong, while errno (a global variable found in <errno.h>) stores a specific code explaining what went wrong.

Use Return Codes First

You should almost always check the return code first. It is your primary "smoke detector." If a function returns a successful value, errno might still contain a leftover error from a completely different, previous function call. Checking errno without a failing return code is like calling the fire department because you smell smoke, even though the alarm hasn't gone off—you might just be smelling your neighbor's barbecue.

Use errno for the "Why"

Once a function returns an error value (like -1), errno becomes your diagnostic tool. It allows your program to make smart decisions. For example, if you try to open a file and it fails, errno tells you if the file is missing (ENOENT) or if you simply don't have permission to see it (EACCES).

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

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

    // 1. Check the return code first
    if (file == NULL) {
        // 2. Now check errno to see WHY it failed
        if (errno == ENOENT) {
            printf("Error: File does not exist.\n");
        } else if (errno == EACCES) {
            printf("Error: Permission denied.\n");
        } else {
            printf("Error: %s\n", strerror(errno));
        }
        return 1;
    }

    fclose(file);
    return 0;
}

The Rule of Thumb

  • Return codes are for flow control (did it work?).
  • errno is for logging and logic branching (how do we handle this specific failure?).

Key takeaway

Use return codes to detect that an error occurred, and use errno immediately afterward to diagnose the specific cause.