Menu

False positive on comparison of IEEE854 floats: plus and minus zero

2022-10-26
2022-11-16
  • Grigory Rechistov

    I have code that performs flushing of subnormal 32-bit floats to plus or minus zeroes.

    static inline float flush(float x) {
            if (fabs(x) < FLT_MIN) {
                    return (x >= 0.0) ? 0.0 : -0.0; // reports "Same value in both branches of ternary operator"
            } else return x;
    }
    

    Cppcheck reports "Same value in both branches of ternary operator." . It considers 0.0 and -0.0 to be equal.
    But they are not. E.g. the following program compiled with GCC returns with 1, meaning the comparison return non-equality.

    int main()
    {
         float p0 = 0.0;
         float m0 = -0.0;
         return p0 == m0;
    }
    

    I am using Cppcheck 2.7 dev built from SHA 31ea13eb0cf396c6b7ff66948808999c74f60f36 at 4th of February.

    Thank you!

     
  • Grigory Rechistov

    This is how invoke the analysis:

    $ cppcheck --enable=all --platform=native -D__GNUC__ -D__linux__ -D__x86_64__ pmzero.c 
    Checking pmzero.c ...
    Checking pmzero.c: __GNUC__=1;__linux__=1;__x86_64__=1...
    pmzero.c:6:41: style: Same value in both branches of ternary operator. [duplicateValueTernary]
                    return (x >= 0.0) ? 0.0 : -0.0; // reports "Same value in both branches of ternary operator"
                                            ^
    

    The input file:

    $ cat pmzero.c 
    #include <math.h>
    #include <float.h>
    
    static inline float flush(float x) {
            if (fabs(x) < FLT_MIN) {
                    return (x >= 0.0) ? 0.0 : -0.0; // reports "Same value in both branches of ternary operator"
            } else return x;
    }
    
     

    Last edit: Grigory Rechistov 2022-10-26
  • Grigory Rechistov

    Also reproduced if I use Cppcheck built from the yesterday's code snapshot (SHA 8672e12a7a5173c0322b2f3341786e6b370afdde)

     
  • Jens Yllman

    Jens Yllman - 2022-11-16

    Hmmm, I wonder how well cppcheck handles other special values in IEEE854.

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.