Home > OS >  Is negative floating point zero guaranteed to evaluate to false in C?
Is negative floating point zero guaranteed to evaluate to false in C?

Time:09-05

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.

CodePudding user response:

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.

  • Related