Argument order to std::min changes compiler output for floating-point

前端 未结 3 1142
礼貌的吻别
礼貌的吻别 2021-02-03 16:39

I was fiddling in Compiler Explorer, and I found that the order of arguments passed to std::min changes the emitted assembly.

Here\'s the example on Godbolt Compiler Expl

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-03 17:08

    To expand on the existing answers that say std::min isn't commutative: Here's a concrete example that reliably distinguishes std_min_xy from std_min_yx. Godbolt:

    bool distinguish1() {
        return 1 / std_min_xy(0.0, -0.0) > 0.0;
    }
    bool distinguish2() {
        return 1 / std_min_yx(0.0, -0.0) > 0.0;
    }
    

    distinguish1() evaluates to 1 / 0.0 > 0.0, i.e. INFTY > 0.0, or true.
    distinguish2() evaluates to 1 / -0.0 > 0.0, i.e. -INFTY > 0.0, or false.
    (All this under IEEE rules, of course. I don't think the C++ standard mandates that compilers preserve this particular behavior. Honestly I was surprised that the expression -0.0 actually evaluated to a negative zero in the first place!

    -ffinite-math-only eliminates this way of telling the difference, and -ffinite-math-only -funsafe-math-optimizations completely eliminates the difference in codegen.

提交回复
热议问题