Question

Possible Duplicate:
NaN Literal in C?

I'm writing a function in ANSI C which receives two numbers as parameters. The parameters are of int or float type. The number may or may not be valid according to my filter. How do I return some value meaning failure? The return type is float. The first thing that come to my mind was the NaN abstract type. But I don't know how to represent it in ANSI C.

(sorry for my bad english. English isn't my native language)

Was it helpful?

Solution

NaN isn't an "abstract type". It's a value of a floating-point datum.

If by "ANSI C" you mean standard C (which is the actual meaning of the term, in as much as it has one), include <math.h> and use the NAN macro to produce a nan, and isnan(x) to detect one.

If by "ANSI C" you actually mean the long-replaced C89 standard (which some people intend, even if it isn't formally correct), you can produce a NaN value with 0./0., and check for one with x != x.

OTHER TIPS

The question the number may not be valid according to my "filter then how do I return some value meaning failure?

Instead of comparing the number against NaN you can use this:

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

As mentioned in the comments, you can use this expression 0.f / 0.f to produce a float NaN value in C89.

You can't do that, you need two variables returned, one for the value, one for the failure flag.

For example you can set thing so the function will return true in case of normal operation. false in case of failure (NaN).

The variable storing the result is passed by reference as a parameter and will hold the returning value in case of success.

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
}

Have something like this

if(your_variable != your_variable)
{
    return 0; //catch 0 as the failure returned value
}
else
{
    //your code
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top