home *** CD-ROM | disk | FTP | other *** search
/ Microsoft Programmer's Library 1.3 / Microsoft-Programers-Library-v1.3.iso / sampcode / c / other / math / matherr.c < prev    next >
Encoding:
C/C++ Source or Header  |  1988-10-31  |  1.8 KB  |  57 lines

  1. /* MATHERR.C illustrates writing an error routine for math functions.
  2.  * The error function must be:
  3.  *      matherr
  4.  *
  5.  * To use matherr, you must turn off the Extended Dictionary flag within
  6.  * the QC environment (Options-Make-Linker Flags) or use the /NOE linker
  7.  * option outside the environment. For example:
  8.  *      QCL matherr.c /link /NOE
  9.  */
  10.  
  11. #include <math.h>
  12. #include <string.h>
  13. #include <stdio.h>
  14.  
  15. main()
  16. {
  17.     /* Do several math operations that cause errors. The matherr
  18.      * routine handles DOMAIN errors, but lets the system handle
  19.      * other errors normally.
  20.      */
  21.     printf( "log( -2.0 ) = %e\n", log( -2.0 ) );
  22.     printf( "log10( -5.0 ) = %e\n", log10( -5.0 ) );
  23.     printf( "log( 0.0 ) = %e\n", log( 0.0 ) );
  24. }
  25.  
  26. /* Routine to handle several math errors caused by passing a negative
  27.  * argument to log or log10 (DOMAIN errors). If this happens, matherr
  28.  * returns the natural or base-10 logarithm of the absolute value of
  29.  * the argument and suppresses the usual error message.
  30.  */
  31. int matherr( struct exception *except )
  32. {
  33.     /* Handle DOMAIN errors for log or log10. */
  34.     if( except->type == DOMAIN )
  35.     {
  36.         if( strcmp( except->name, "log" ) == 0 )
  37.         {
  38.             except->retval = log( -(except->arg1) );
  39.             printf( "Special: using absolute value: %s: DOMAIN error\n",
  40.                     except->name );
  41.             return 1;
  42.         }
  43.         else if( strcmp( except->name, "log10" ) == 0 )
  44.         {
  45.             except->retval = log10( -(except->arg1) );
  46.             printf( "Special: using absolute value: %s: DOMAIN error\n",
  47.                     except->name );
  48.             return 1;
  49.         }
  50.     }
  51.     else
  52.     {
  53.         printf( "Normal: " );
  54.         return 0;    /* Else use the default actions */
  55.     }
  56. }
  57.