Start New Discussion within our Software Development Community

For all functions, a domain error occurs if an input argument is outside the domain over which the mathematical function is defined. On a domain error, the function returns an implementation-defined value.

#include <stdio.h>
#include <errno.h>
#include <math.h>
#define POSITIVE 25
#define NEGATIVE -25
 
int main()
{
     double ret;
 
     errno = 0;
     ret = sqrt(NEGATIVE);
     if (errno == EDOM) /*EDOM Signifies Domain Error*/
          printf("Domain Error : Invalid Input To Function\n");
     else
          printf("Valid Input To Function\n");
 
     errno = 0;
     ret = sqrt(POSITIVE);
 
     if (errno == EDOM)
          printf("Domain Error : Invalid Input To Function\n");
     else
          printf("Valid Input To Function\n");
 
     return 0;
}
 
/***  
     *  Output
     *  Domain Error:Invalid Input To Function
     *  Valid Input To Function
***/

Consider also using perror to diagnose the problem.

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

void test(double value)
{
   double ret;
   errno = 0;
   ret = sqrt(value);
   if ( errno )
   {
      perror("sqrt");
   }
   else
   {
      printf("ret = %g\n", ret);
   }
}

int main()
{
   test(-25);
   test(25);
}

/* my output
sqrt: Domain error
ret = 5
*/
The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.