errno is not being set to EDOM for domain error of sqrt() function in windows It shows correctly on Linux but failed on windows (Using GCC 7.4) ...
#include <stdio.h>
#include <errno.h>
#include <math.h>
int main () {
double val;
errno = 0;
val = sqrt(-10);
if(errno == EDOM) {
printf("Invalid value \n");
} else {
printf("Valid value\n");
}
errno = 0;
val = sqrt(10);
if(errno == EDOM) {
printf("Invalid value\n");
} else {
printf("Valid value\n");
}
return(0);
}
Expected result : Invalid value Valid value Actual result : Valid value Valid value
Initializing ErrnoYour program should always initialize errno to 0 (zero) before calling a function because errno is not reset by any library functions. Check for the value of errno immediately after calling the function that you want to check. You should also initialize errno to zero after an error has occurred.
yields the system error string corresponding to errno . Many system or library calls set errno if they fail, to indicate the cause of failure. They usually do not set errno to zero if they succeed and may set errno to a non-zero value on success.
Indeed we should only check errno in the case where an error occurred. This is because if no error occurred, then it is still possible that errno will contain a non-zero value (e.g. if an error occurred during the execution of a library call but the error was recovered).
Upon successful completion, read(), pread() and readv() return a non-negative integer indicating the number of bytes actually read. Otherwise, the functions return -1 and set errno to indicate the error.
The math functions are not required to set errno
. They might, but they don't have to. See section 7.12.1 of the C standard. Theoretically you can inspect the value of the global constant math_errhandling
to find out whether they will, but that's not fully reliable on any implementation I know of, and may not even be defined (it's a macro, so you can at least use #ifdef
to check for it).
Instead, you can check whether the input is negative before calling sqrt
, or (if your implementation properly supports IEEE 754 in detail) you can check whether the output is NaN (using isnan
) afterward.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With