1

I know that 0.0 == -0.0 and that the C standard says if(a) is equivalent to if(a!=0), but:

Is if(-0.0) guaranteed to evaluate as false by the standard? Would an implementation be buggy if if(-0.0) is evaluated as true?

I guess the key point here is whether the if(a!=0) meaning of if(-0.0) must be understood as exactly the same != operator as in floating point, in which case there would be guarantee that it must be false.

cesss
  • 852
  • 1
  • 6
  • 15
  • 1
    Sometimes using +0.0 and -0.0 have a [different](https://stackoverflow.com/questions/25332133/what-operations-and-functions-on-0-0-and-0-0-give-different-arithmetic-results) arithmetic result in code, but not with `if()`. – chux - Reinstate Monica Sep 04 '22 at 13:13
  • Note: `-0.0` is a double value, not a floating point value. To make it a floating point value write it as: `-0.0f` Notice the trailing 'f' – user3629249 Sep 06 '22 at 18:46
  • @user3629249 : Both `double` and `float` are floating point types, just like all the formats defined by IEEE 754. – cesss Sep 06 '22 at 20:50

1 Answers1

5

C 2018 6.8.4.1 specifies the behavior of the if statement, with its if … else form. Paragraph 2 says:

In both forms, the first substatement is executed if the expression compares unequal to 0…

Per the floating point model in C 2018 5.2.4.2.2 paragraphs 2 and 3 (which contain mathematical typography I will not reproduce here but say a floating-point number is defined by multiplying a sign +1 or −1 by a scaled power of the floating-point base and a sum of its digits each appropriately scaled for its position), the mathematical value of −0 is zero, the same as +0, so it compares equal to zero. Therefore if (-0.) will not execute the first substatement.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312