errno.h in C Language
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 | int x = -1; |
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 adoublecan represent.
When using mathematical functions, you can compare the value of errno with EDOM and ERANGE to determine the type of error that occurred.