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

Warn for wrong for nested loops #18668

Open
dlangBugzillaToGithub opened this issue Sep 12, 2013 · 0 comments
Open

Warn for wrong for nested loops #18668

dlangBugzillaToGithub opened this issue Sep 12, 2013 · 0 comments

Comments

@dlangBugzillaToGithub
Copy link

bearophile_hugs reported this on 2013-09-12T12:39:34Z

Transferred from https://issues.dlang.org/show_bug.cgi?id=11018

Description

A blog post that shows some of the warnings of the Clang compiler:

http://blog.llvm.org/2013/09/clang-warnings.html

It contains:
<<

for (int i = 0; i < size_; ++i) {
  for (int j = 1; j < size_; ++i) {
    ...
  }
}


This double nested loop gives bubble sort its n^2 running time.  Rather, in this case, an infinite running time.  Note the increment in both of the loops happen on i, even in the inner loop.  j is never touched, either here or inside the loop.  -Wloop-analysis will give a warning when all the variables inside a for loop conditional does not change during the loop iteration. Only in Clang.
>>

D has foreach that avoids most of similar bugs:


void main() {
    enum int size_ = 5;
    foreach (i; 0 .. size_) {
        foreach (i; 0 .. size_) {
        }
    }
}


test.d(4): Error: is shadowing declaration test.main.i

But in D you can't always use foreach (unless you also use iota()), sometimes you have to use for loops (like when the increment is not 1):


void main() {
    enum size_ = 5;
    for (int i = 0; i < size_; i += 2) {
        for (int j = 1; j < size_; i += 2) {}
    }
}


Perhaps it's a good idea for the D compiler to warn for such wrong loops, as Clang does.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant