Synopsis: | Don't compare floats of different types. |
Language: | C |
Severity Level: | 6 |
Category: | Expressions |
Description: |
Justification Difference in precision may result in unexpected result. Example float test1 = 10.1; double test2 = 10.1; if (test1 > test2) /* WRONG: TRUE, because test1 = 10.1000038 and test2 = 10.1 */ if ((double)test1 > test2) /* WRONG: TRUE, because test1 = 10.1000038 and test2 = 10.1 */ if (test1 > (float)test2) /* RIGHT: FALSE, because test1 = test2 = 10.1000038 */ Note Note that in the example above casting will remove the violation but only casting to the lower precision type will make the numbers comparable (at the cost of information loss). |