The errno Variable

The errno.h header file declares the errno variable, which is an int used to store error codes (positive integers).

If errno has a non-zero value, it indicates that an error occurred during the execution of a program.

1
2
3
4
5
6
7
8
9
int x = -1;
errno = 0; // Reset errno to 0

int y = sqrt(x); // Attempt to calculate the square root of a negative number

if (errno != 0) {
fprintf(stderr, "sqrt error; program terminated.\n");
exit(EXIT_FAILURE);
}

In this example, calculating the square root of a negative number is invalid, which sets errno to a non-zero value.

To check for errors after calling a function, always reset errno to 0 before the function call to avoid interference from other functions.

Error Macros

The value of errno is often one of two macros defined in errno.h: EDOM or ERANGE. These represent possible errors when using mathematical functions.

  • Domain Error (EDOM): This occurs when an argument passed to a function is outside its valid range, such as passing a negative number to sqrt().
  • Range Error (ERANGE): This happens when the return value of a function is too large to be represented by its return type, like passing 1000 to exp(), since ( e^{1000} ) exceeds what a double can represent.

When using mathematical functions, you can compare the value of errno with EDOM and ERANGE to determine the type of error that occurred.