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

The global `errno` variable

The global errno variable

What you'll learn: How to use the standard library's hidden messenger to find out exactly why a function call failed.

In C, many functions return a simple -1 or NULL when something goes wrong. While this tells you that a failure happened, it doesn't tell you why. Was the file missing? Did you run out of memory? To solve this, the C standard library uses a global variable called errno.

The Doctor’s Clipboard

Imagine you are a doctor at a busy hospital. You ask a nurse to perform a blood test. The nurse returns and simply says, "I couldn't do it." That isn't very helpful. However, if the nurse leaves a note on a shared clipboard in the hallway saying "Patient refused" or "Needle broken," you know exactly how to fix the situation.

In this analogy, errno is the shared clipboard. It is a global integer defined in the <errno.h> header. When a system function hits a snag, it writes a specific error code into errno before returning its failure signal to you.

Seeing errno in Action

To use errno, you must include <errno.h>. Because it is a global variable, its value stays there until another function overwrites it. Therefore, you should always check its value immediately after a function fails.

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

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

    if (file == NULL) {
        // Something went wrong! Let's check the "clipboard"
        printf("Error code: %d\n", errno);
        
        // Use strerror to turn that number into a human message
        printf("Meaning: %s\n", strerror(errno));
    }

    return 0;
}

Important Habits

There are two golden rules when working with errno:

  1. Check for failure first: Only look at errno if the function's return value indicates an error (like returning NULL). If a function succeeds, it doesn't necessarily clear errno, so you might see a "ghost" error from a previous operation.
  2. Act fast: If you call another library function before reading errno, that second function might overwrite the error code from the first one.

By reading this hidden variable, your programs move from simply knowing "it didn't work" to understanding the specific reason for the failure.

Key takeaway

The errno variable is a global error code that provides the specific reason for a function's failure, accessible by including <errno.h>.