This rule raises an issue when increment (++) or decrement (--) operators are used with floating-point variables.
Increment and decrement operators (++ and --) shouldn’t be used with floating-point variables (like float or
double). While the language allows it, the usage is not idiomatic, and most developers intuitively expect x++ to apply to
integer types. Using it on a float violates this common expectation and can lead to misleading code.
Floating-point arithmetic has some non-intuitive properties, which can lead to unexpected bugs. For example, the following loop will not terminate.
This happens because float has only 24 bits of precision (mantissa) and once a number gets large enough, adding 1.0 becomes
insignificant and the increment operation does nothing:
for (float x = 16_000_000; x < 17_000_000; x++) {
// ...
}
// The loop does not terminate
The problem would not occur if int is used instead of float, even though both types occupy 32 bits:
for (int x = 16_000_000; x < 17_000_000; x++) {
// ...
}
// This loop terminates.
Using the compound assignment operators (+= and -=) makes the intent clearer and avoids the surprising use of
++ and -- on floating-point types.
float x = 0f; double y = 1.0; x++; y--;
float x = 0f; double y = 1.0; x += 1.0; y -= 1.0;