C Library Macros - EDOM
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
- NA
Return Value
- NA
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:
- we try to compute the square root of -1, which is an out-of-domain operation because negative numbers have no real square root.
sqrtThe function detects this domain error and setserrnotoEDOM.- We check
errno, and if it isEDOM, we print the corresponding error message.
Related math functions
The following are some math functions that may set errno is EDOM :
sqrt(x): Whenx < 0, setserrnoisEDOM.log(x): Whenx <= 0, setserrnoisEDOM.asin(x)andacos(x): Whenxwhen not in the range [-1, 1], setserrnoisEDOM.pow(x, y): Whenx < 0andywhen not an integer, setserrnoisEDOM.
Usage notes
- 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), checkerrno. - Initialization
errno: before calling the function, seterrnoto 0 to ensure the error code comes from this call and not a leftover from a previous one. - Thread Safety: in multithreaded programs,
errnois usually implemented as Thread-Local Storage (TLS), ensuring each thread has an independenterrnovalues.
Other related error codes
Besides EDOM, also defines other error codes related to math functions:
ERANGE: result out of range. For example, computingexp(1000)may cause overflow and seterrnotoERANGE.EILSEQ: illegal byte sequence. When handling wide-character or multibyte-character functions, the input data contains an invalid character sequence.
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 -