How to determine NaN value in ANSI C?

Possible duplicate:
NaN Literal in C?

I am writing a function in ANSI C that takes two numbers as parameters. Parameters are of type int or float . The number may or may not be valid according to my filter. How do I return a failure value? Return type float . The first thing that occurred to me was the abstract type of NaN . But I do not know how to present it in ANSI C.

(sorry for my bad english. English is not my native language)

+8
c floating-point c89 nan
source share
4 answers

NaN is not an "abstract type". This is the value of the floating point.

If according to "ANSI C" you mean the C standard (which is the actual meaning of the term, since it has one), include <math.h> and use the NAN macro to create nan and isnan(x) for detection.

If β€œANSI C” actually means the long-superseded C89 standard (which some people intend, even if it is not formally correct), you can create a NaN value using 0./0. and check it with x != x .

+12
source share

Question number may be invalid according to my "filter", then how can I return some value indicating failure?

Instead of comparing a number with NaN, you can use this:

 if (x != x) // x is NaN 

As stated in the comments, you can use this expression 0.f / 0.f to get the float NaN value in C89.

+4
source share

You cannot do this, you need to return two variables, one for the value, one for the failure flag.

For example, you can set the value so that the function returns true in case of normal operation. false in case of failure (NaN).

A variable that stores the result is passed by reference as a parameter and will hold the return value if successful.

 BOOL myFunction(int inInt, float inFloat, float *outResult) { /* PROCESSING HERE */ // in case of failure if( /* failure condition here */ ) { *outResult = 0; return false; } *outResult = /* your result */ return true; } // how to use the function int a; float b; float result; BOOL success; success = myFunction(a, b, &result); if(success) { // do whatever with your "result" } else { // NaN } 
+2
source share

There is something like this

 if(your_variable != your_variable) { return 0; //catch 0 as the failure returned value } else { //your code } 
-2
source share

All Articles