Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Library Macros – EDOM

C Library Macros - EDOM

C Standard Library - <errno.h> C Standard Library -

Description

C Library Macros EDOM represents a domain error, which occurs when an input argument is outside the domain defined by a mathematical function; errno is set to EDOM.

EDOM is a macro in the C standard library, defined in header. It is used to indicate a mathematical function argument domain error, i.e., the function argument is outside the mathematical domain. This usually occurs when math library functions (such as sqrt, log, asin ) receive illegal input arguments.

Declaration

The following is an example of using EDOM example that demonstrates how to handle math function argument domain errors:



#define EDOM some_value

Parameters

Return Value

Example

The following example demonstrates the use of the EDOM macro.

Example

#include

#include

#include

int

main

(

)

{

   

double

x

=

1.0

;

   

double

result

;

   

// Clear previous errors

    errno

=

0

;

   

// Call the sqrt function; passing a negative value causes a domain error

    result

=

sqrt

(

x

)

;

   

if

(

errno

==

EDOM

)

{

       

printf

(

"Error: sqrt() domain error, input value is %f\n"

,

x

)

;

   

}

else

{

       

printf

(

"The square root of %f is %f\n"

,

x

,

result

)

;

   

}

   

return

0

;

}

Let's compile and run the above program, which will produce the following result:



The square root of -1.000000 is nan

In this example:

  1. we try to compute the square root of -1, which is an out-of-domain operation because negative numbers have no real square root.
  2. sqrt The function detects this domain error and sets errno to EDOM.
  3. We check errno , and if it is EDOM, we print the corresponding error message.

Related math functions

The following are some math functions that may set errno is EDOM :

Usage notes

  1. Check the return value: after calling a math function that may produce a domain error, check the return value, and when the function returns a special value (such as NaN), check errno.
  2. Initialization errno: before calling the function, set errno to 0 to ensure the error code comes from this call and not a leftover from a previous one.
  3. Thread Safety: in multithreaded programs,errno is usually implemented as Thread-Local Storage (TLS), ensuring each thread has an independent errno values.

Other related error codes

Besides EDOM, also defines other error codes related to math functions:

In summary,EDOM is an important macro for handling math function argument domain errors, helping programmers detect and handle illegal input arguments. Through the reasonable use of errno and its related macros, more robust and reliable code can be written.

C Standard Library - <errno.h> C Standard Library -