[Issue 11018] New: Warn for wrong for nested loops

d-bugmail at puremagic.com d-bugmail at puremagic.com
Thu Sep 12 12:39:35 PDT 2013


http://d.puremagic.com/issues/show_bug.cgi?id=11018

           Summary: Warn for wrong for nested loops
           Product: D
           Version: D2
          Platform: All
        OS/Version: All
            Status: NEW
          Keywords: diagnostic
          Severity: enhancement
          Priority: P2
         Component: DMD
        AssignedTo: nobody at puremagic.com
        ReportedBy: bearophile_hugs at eml.cc


--- Comment #0 from bearophile_hugs at eml.cc 2013-09-12 12:39:34 PDT ---
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.

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list