C:C Error Handling: Return Codes, errno, and perror
C•Error Handling

C Error Handling: Return Codes, errno, and perror

Since C has no exceptions, error handling relies on return status codes and the global errno variable from <errno.h>.

Syntax

#include <errno.h> if (res == -1) { perror("Operation failed"); }

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
errnoGlobal VariableSet by system calls when an error occurs.
perror(str)FunctionPrints error message string corresponding to current errno.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing C locally:

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

int safeDivide(int numerator, int denominator, int* result) {
    if (denominator == 0) {
        return -1; // Error code for invalid division
    }
    *result = numerator / denominator;
    return 0; // Success
}

int main(void) {
    int res = 0;

    // 1. Success case
    if (safeDivide(100, 5, &res) == 0) {
        printf("100 / 5 = %d\n", res);
    }

    // 2. Error case
    if (safeDivide(50, 0, &res) != 0) {
        printf("[ERROR] Division by zero prevented cleanly!\n");
    }

    return 0;
}
Expected Output:
100 / 5 = 20
[ERROR] Division by zero prevented cleanly!

How It Works: Step-by-Step

  • Lines 5-11: safeDivide returns status integer (0 = success, -1 = error).
  • Lines 16-24: Caller checks return code before using result.

Key Concepts

  • Idiomatic C functions return 0 on success and negative values or NULL on error.
  • The actual computation result is returned via output pointer parameters.

Common Mistake: Ignoring function return codes

Ignoring return codes leads to operating on invalid data after a failure occurred.

❌ Incorrect
safeDivide(50, 0, &res);
printf("%d", res); // Uses uninitialized/invalid result!
✅ Correct
if (safeDivide(50, 0, &res) == 0) { printf("%d", res); }

Related C Tutorials & Compiler

Run and test C on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C Online Compiler