Create rule S2193: "while" loop counters should not have floating type (#4736)
* Add rust to rule S2193 * Update RSPEC --------- Co-authored-by: yassin-kammoun-sonarsource <yassin-kammoun-sonarsource@users.noreply.github.com> Co-authored-by: yassin-kammoun-sonarsource <yassin.kammoun@sonarsource.com>
This commit is contained in:
parent
90a9b01d26
commit
dc98004888
6
rules/S2193/rust/metadata.json
Normal file
6
rules/S2193/rust/metadata.json
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"title": "\"while\" loop counters should not have floating type",
|
||||||
|
"tags": [
|
||||||
|
"clippy"
|
||||||
|
]
|
||||||
|
}
|
42
rules/S2193/rust/rule.adoc
Normal file
42
rules/S2193/rust/rule.adoc
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
== Why is this an issue?
|
||||||
|
|
||||||
|
When using a floating-point ``++while++`` loop counter, an accumulation of rounding errors may result in a mismatch between the expected and actual number of iterations.
|
||||||
|
|
||||||
|
Even if floating-point loop counters appears to behave correctly on one implementation, it may give a different number of iterations on another implementation.
|
||||||
|
|
||||||
|
== How to fix it
|
||||||
|
|
||||||
|
To fix the issue, use an integer loop counter instead. This avoids the accumulation of rounding errors and ensures that the loop iterates the expected number of times.
|
||||||
|
|
||||||
|
=== Code examples
|
||||||
|
|
||||||
|
==== Noncompliant code example
|
||||||
|
|
||||||
|
[source,rust,diff-id=1,diff-type=noncompliant]
|
||||||
|
----
|
||||||
|
fn main() {
|
||||||
|
let mut counter = 0.0;
|
||||||
|
while counter < 10.0 {
|
||||||
|
println!("Counter: {}", counter);
|
||||||
|
counter += 1.0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
----
|
||||||
|
|
||||||
|
==== Compliant solution
|
||||||
|
|
||||||
|
[source,rust,diff-id=1,diff-type=compliant]
|
||||||
|
----
|
||||||
|
fn main() {
|
||||||
|
let mut counter = 0;
|
||||||
|
while counter < 10 {
|
||||||
|
println!("Counter: {}", counter);
|
||||||
|
counter += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
----
|
||||||
|
|
||||||
|
== Resources
|
||||||
|
=== Documentation
|
||||||
|
|
||||||
|
* Clippy Lints - https://rust-lang.github.io/rust-clippy/master/index.html#while_float
|
Loading…
x
Reference in New Issue
Block a user