Skip to content
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

FP explicit_counter_loop: var incremented before usage #6074

Closed
matthiaskrgr opened this issue Sep 22, 2020 · 2 comments
Closed

FP explicit_counter_loop: var incremented before usage #6074

matthiaskrgr opened this issue Sep 22, 2020 · 2 comments
Labels
C-bug Category: Clippy is not doing the correct thing

Comments

@matthiaskrgr
Copy link
Member

I tried this code:

pub fn main() {
    let mut i = 0;
    let v = vec!["a", "b", "c"];
    for x in &v {
        i += 1;
        println!("{}", i)
    }
}

explicit_counter_loop will trigger here and suggest to use .iter().enumerate().
The problem is that we increment BEFORE using (and not at the end of the loop) so the first iteration will print 1 and not 0 as it would with .enumerate().
This newly suggested code is off by one as can be seen here:

pub fn main() {
    let mut i = 0;
    let v = vec!["a", "b", "c"];
    for (x, _) in v.iter().enumerate() {
        i += 1;
        println!("i is {} but x is {}", i, x)
    }
}
i is 1 but x is 0
i is 2 but x is 1
i is 3 but x is 2

clippy 0.0.212 (fb1dc34 2020-09-21)

@matthiaskrgr matthiaskrgr added C-bug Category: Clippy is not doing the correct thing I-suggestion-causes-error Issue: The suggestions provided by this Lint cause an ICE/error when applied labels Sep 22, 2020
@ebroto

This comment has been minimized.

@matthiaskrgr matthiaskrgr removed the I-suggestion-causes-error Issue: The suggestions provided by this Lint cause an ICE/error when applied label Sep 22, 2020
bors added a commit that referenced this issue Sep 24, 2020
…iaskrgr

Fix a FP in `explicit_counter_loop`

Fixes #4677 and #6074

Fix a false positive in `explicit_counter_loop` where the loop counter is used after incremented, adjust the test so that counters are incremented at the end of the loop and add the test for this false positive.

---

changelog: Fix a false positive in `explicit_counter_loop` where the loop counter is used after incremented
@ebroto
Copy link
Member

ebroto commented Sep 25, 2020

Fixed by #6076

@ebroto ebroto closed this as completed Sep 25, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
C-bug Category: Clippy is not doing the correct thing
Projects
None yet
Development

No branches or pull requests

2 participants