If I copy a float to another variable, will they be equal?

后端 未结 5 1050
猫巷女王i
猫巷女王i 2021-01-30 00:11

I know that using == to check equality of floating-point variables is not a good way. But I just want to know that with the following statements:



        
5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-30 00:28

    Besides the assert(NaN==NaN); case pointed out by kmdreko, you can have situations with x87-math, when 80bit floats are temporarily stored to memory and later compared to values which are still stored inside a register.

    Possible minimal example, which fails with gcc9.2 when compiled with -O2 -m32:

    #include 
    
    int main(int argc, char**){
        float x = 1.f/(argc+2);
        volatile float y = x;
        assert(x==y);
    }
    

    Godbolt Demo: https://godbolt.org/z/X-Xt4R

    The volatile can probably be omitted, if you manage to create sufficient register-pressure to have y stored and reloaded from memory (but confuse the compiler enough, not to omit the comparison all-together).

    See GCC FAQ reference:

    • Why floating-point results change with optimization levels or different compiler versions or different target architectures?

提交回复
热议问题