You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
=== Increment and decrement operators shouldn't be used with floating-point variables
1
+
This rule raise an issue when increment (`{plus}{plus}`) or decrement (`--`) operators are used with floating-point variables.
2
+
3
+
== Why is this an issue?
3
4
4
5
Increment and decrement operators (`{plus}{plus}` and `--`) shouldn't be used with floating-point variables (like `float` or `double`).
5
6
While the language allows it, the usage is not idiomatic, and most developers intuitively expect `x{plus}{plus}` to apply to integer types.
6
7
Using it on a float violates this common expectation and can lead to misleading code.
7
8
8
-
9
-
10
-
11
-
// If you want to factorize the description uncomment the following line and create the file.
12
-
//include::../description.adoc[]
13
-
14
-
== Why is this an issue?
9
+
=== What is the potential impact?
15
10
16
11
Floating-point arithmetic has some non-intuitive properties, which can lead to unexpected bugs.
17
12
For example, the following loop will not terminate:
@@ -26,7 +21,6 @@ for (float x = 16_000_000; x < 17_000_000; x++) {
26
21
27
22
This happens because `float` has only 24 bits of precision (mantissa) and once a number gets large enough, adding `1.0` becomes insignificant.
28
23
The increment operation effectively does nothing.
29
-
30
24
The problem would not occur if `int` is used instead of `float`, even though both types occupy 32 bits:
31
25
32
26
[source,java]
@@ -40,13 +34,11 @@ for (int x = 16_000_000; x < 17_000_000; x++) {
40
34
Using the compound assignment operators (`{plus}=` and `-=`) makes the intent clearer and avoids the surprising use of `{plus}{plus}` and `--` on floating-point types.
0 commit comments