Is relational comparison between int and float directly possible in C?

This is generally (i.e., always) a bad idea. As you suspected, the comparison from 3 to 3.0000001 will indeed fail.

What most people do, if an int-float comparison is really necessary, is pick some threshold of tolerance and go with that, like so:

int x = 3;
float y = 3.0;

// some code here

float difference = (float) x - y;
float tolerableDifference = 0.001;

if ((-tolerableDifference <= difference) && (difference <= tolerableDifference)) {
    // more code
}

Leave a Comment