-
Notifications
You must be signed in to change notification settings - Fork 33
Create rule S8346: Increment and decrement operators (++/--) should not be used with floating point variables. #5951
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Conversation
efbcbb6 to
0f80326
Compare
|
|
| ---- | ||
|
|
||
| This happens because `float` has only 24 bits of precision (mantissa) and once a number gets large enough, adding `1.0` becomes insignificant. | ||
| The increment operation effectively does nothing. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Let's merge it with the previous sentence to improve flow. For example, "adding 1.0 becomes insignificant and the operation does nothing"
| // This loop terminates. | ||
| ---- | ||
|
|
||
| Using the compound assignment operators (`{plus}=` and `-=`) makes the intent clearer and avoids the surprising use of `{plus}{plus}` and `--` on floating-point types. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
How about we move this sentence to "How to fix it"?





You can preview this rule here (updated a few minutes after each push).
Review
A dedicated reviewer checked the rule description successfully for:
Description
Increment and decrement operators (
++and--) shouldn't be used with floating-point variables (likefloatordouble). While the language allows it, the usage is not idiomatic and most developers intuitively expectx++to apply to integer types. Using it on a float violates this common expectation and can lead to misleading code.In particular 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
floathas only 24 bits of precision and once a number gets large enough, adding1.0becomes insignificant.The problem would not occur if
intis used instead offloat, even though both bytes occupy 32 bits.Noncompliant code
Compliant code