Home > Software design >  How to check if a float value is null in C?
How to check if a float value is null in C?

Time:10-03

I'm using C and OpenGL and I'm having trouble with trying to compare a GLfloat type list with NULL:

int i = 0;
int m = 0;

    void glPolygonMove(GLfloat PolygonCoords[i][m], GLfloat xPosition, GLfloat yPosition)   // function to add x and y to poly pos
{
        for(int i = 0; PolygonCoords[i][m] != NULL && PolygonCoords[i][m   1] != NULL; i  ){
                PolygonCoords[i][m]  = xPosition;
                PolygonCoords[i][m   1]  = yPosition;
        }   

}

When I compile the code, GCC signals that it can't compare Float's to Null's. Is there any other way that I can compare or know when the value of a float list[i] == nothing?

PS: GLfloat type is the same as float.

CodePudding user response:

You seem to be mixing two mistakes here:

  • how to check that a floating point value is zero?
  • zero does not equal null

Let's start with the latter: the term null is the "initialisation" value for pointers, which point at nothing. It is not the same as the number value 0 (zero).
Next: it makes no sense checking if a floating point value equals zero, because in most programming languages, 1.0/3*3 - 1 is not equal to zero, but it will be equal to some very small value, depending on the accuracy of the computer. Therefore it is better checking that a value is smaller than a small margin value (like 1E-15 or something).

CodePudding user response:

Floating point numbers have a special way to encode invalid flags. There are two types of invalid floating numbers: a NaN (not-a-number) and infinite.

In ISO C99 and POSIX 2001 you can use isfinite(fval) which returns a nonzero value if the value fval is not NaN or infinite.

You can also use isnan(fval) or isinf(fval) if you need more granularity.

  •  Tags:  
  • c
  • Related