Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why errno is not set to EDOM even sqrt takes out of domain arguement?

Tags:

c

errno

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

like image 801
Tilak_Chad Avatar asked May 21 '19 17:05

Tilak_Chad


People also ask

Do I need to set errno to 0?

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.

Is errno set on success?

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.

Should I set errno?

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).

Does Read set errno?

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.


1 Answers

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.

like image 79
zwol Avatar answered Nov 15 '22 04:11

zwol