Math library functions and error checking

Dave Decot decot at hpisod2.HP.COM
Tue May 8 09:54:08 AEST 1990


> What is the correct method to check whether an exception (overflow,
> invalid arguments, etc.) occurred during the execution of a C math
> library function (such as sqrt() or sin())?
> 
> Do I have to test the result against NaN, or do I have to check errno
> (EDOM)?  If the latter is true, is errno cleared automatically on
> success or do I have to clear it before calling the function?

Given the current confused state of affairs...

   For System V conforming systems, errno is set appropriately, and NaN
   (or infinities, or zero, where appropriate) may or may not be returned.

   For IEEE 754/854 conforming systems, NaN, appropriate infinities, and zero
   are returned as required, but errno may or may not be set.

   matherr() may or may not be called if provided by the application

...I would recommend following the suggestions given in X/Open Portability
Guide, Issue 3 (XPG3); namely:

    An application wishing to check for error situations should set
    errno to zero before calling the function.  If errno is set on
    return, or the return value is NaN (or for some functions, zero,
    or HUGE_VAL, where appropriate), an error has occurred.

    Under error conditions on some implementations, an error message is
    printed on stderr.   On such implementations, this error handling
    can be suppressed by providing a matherr() function, such as the following,
    as part of the application code:

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

	#ifdef DOMAIN

	   int matherr(except)
	   struct exception *except;
	   {
		switch (except->type)
		{
			case DOMAIN:
			case SING:
				errno = EDOM;
				return 1;

			    defauilt:
				errno = ERANGE;
				return 1;
		}
	    }

	#endif /* DOMAIN */

Dave Decot
HP



More information about the Comp.lang.c mailing list