7.2 Error Detection

To help you detect run-time errors, the <errno.h> header file defines the following two symbolic values that are returned by many (but not all) of the mathematical functions:

When using the math functions, you can check the external variable errno for either or both of these values and take the appropriate action if an error occurs.

The following program example checks the variable errno for the value EDOM, which indicates that a negative number was specified as input to the function sqrt:

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

main()
{
   double input, square_root;

   printf("Enter a number: ");
   scanf("%le", &input);
   errno = 0;
   square_root = sqrt(input);

   if (errno == EDOM)
      perror("Input was negative");
   else
      printf("Square root of %e = %e\n",
              input, square_root);
}

If you did not check errno for this symbolic value, the sqrt function returns 0 when a negative number is entered. For more information about the <errno.h> header file, see Chapter 4.


Previous Page | Next Page | Table of Contents | Index