I do not understand why you ask whether the same two numbers can be compared. Why would you not expect a comparison such as 3 > 3
to work, even though 3 is the same as 3? The >
operator returns true if the left side is greater than the right side, and it returns false otherwise. In this case, .8
is not greater than a
, so the result is false.
Other people seem to have assumed that you are asking about some floating-point rounding issue. However, even with exact mathematics, .8 > .8
is false, and that is the result you get with the code you showed; the else branch is taken. So there is no unexpected behavior here to explain.
What is your real question?
In case you are asking about floating-point effects, some information is below.
In C source, the text “.8” stands for one of the numbers that is representable in double-precision that is nearest .8. (A good implementation uses the nearest number, but the C standard allows some slack.) In the most common floating-point format, the nearest double-precision value to .8 is (as a hexadecimal floating-point numeral) 0x1.999999999999ap-1, which is (in decimal) 0.8000000000000000444089209850062616169452667236328125.
The reason for this is that binary floating-point represents numbers only with bits that stand for powers of two. (Which powers of two depends on the exponent of the floating-point value, but, regardless of the exponent, every bit in the fraction portion represents some power of two, such as .5, .25, .125, .0625, and so on.) Since .8 is not an exact multiple of any power of two, then, when the available bits in the fraction portion are all used, the resulting value is only close to .8; it is not exact.
The initialization float a = .8;
converts the double-precision value to single-precision, so that it can be assigned to a. In single-precision, the representable number closest to .8 is 0x1.99999ap-1 (in decimal, 0.800000011920928955078125).
Thus, when you compare “.8” to a, you find that .8 > a
is false.
For some other values, such as .7, the nearest representable numbers work out differently, and the relational operator returns true. For example, .7 > .7f
is true. (The text “.7f” in source code stands for a single-precision floating-point value near .7.)