Can I get -Wfloat-equal behavior for all comparisons except literal zero?

I would like to include -Wfloat-equal in my build options (which is the GCC flag that gives a warning when two floating-point numbers are compared using the == or! = Operators). However, in several library header files that I use, and in a large part of my own code, I often want to fork for non-zero float or double values ​​using if (x) or if (x != 0) or variants of this.

Since in these cases I am absolutely sure that the value is zero - the checked values ​​are the result of an explicit initialization of zero, calloc , etc. - I see no drawback in using this comparison, but not a much more expensive and less readable call to my function near(x, 0) .

Is there a way to get the -Wfloat-equal effect for all other floating point comparison comparisons, but let them go through unchanged? There are enough of them in the library header files that they can significantly pollute my warning output.

+4
source share
3 answers

From the question you ask, it seems that the warning is completely appropriate. If you compare exact zero to check if the original zero value has a calloc value (which is actually incorrect from the point of view of pure C, but works on any IEEE 754 compatible implementation), you can get false positives from non-zero values ​​rounded to zero. In other words, this seems like the wrong code.

+2
source

This is pretty awful, but it avoids the warning:

 #include <functional> template <class T> inline bool is_zero(T v) { return std::equal_to<T>()(v, 0); } 

GCC does not report warnings for system headers, and this causes an equality check in the system header.

+2
source

This discussion looks like it is being applied ...

Selectively disable GCC warnings for part of a translation unit only?

0
source

Source: https://habr.com/ru/post/1341380/


All Articles