Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The isinf macro tests an input floating point value for infinity. isinf(\x) returns 1 if x is infinity, -1 if x is negative infinity, and 0 otherwise.

isnan tests if an input is NaN. isnan(\x) is 1 if x is NaN, and 0 otherwise.

...

This can be a problem if an invalid value is entered for val and subsequently used for calculations or as control values. The user could, for example, input the values strings "INF", "INFINITY", or "NAN" (case insensitive) on the command line, which would be parsed by scanf into the floating-point representations of infinity and NaN. All subsequent calculations using these values would be invalid, possibly crashing the program and enabling a DOS attack.

...

The following code first validates the input float before using it. The value is tested to ensure that it is within the acceptable range of MIN_VAL to MAX_VAL (and is therefore w neither infinity nor negative infinity )nor NaN.

Code Block
bgColor#ccccff
double val;

scanf("%g", &val);

int k=isinf(x);

if(val<MIN_VAL || val>MAX_VAL)  (k==1){

/* handle infinity error */

}

if (k==-1){

/* handle rangenegative infinity error */

}

if(isnan(val)) /* test NaN */

{

/* handle NaN error */

}

 

Exceptions

Occasionally, NaN or infinity may be acceptable or expected inputs to a program. If this is the case, then explicit checks may not be necessary. Such programs must, however, be prepared to handle these inputs gracefully and not blindly use them in mathematical expressions where they are not appropriate.

...

Wiki Markup
\[[IEEE 754|AA. C References#IEEE 754 2006]\]
\[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\]
\[[IEEE 1003.1, 2004|AA. C References#IEEE 1003]\]