D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 11018 - Warn for wrong for nested loops
Summary: Warn for wrong for nested loops
Status: NEW
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: All All
: P4 enhancement
Assignee: No Owner
URL:
Keywords: diagnostic
Depends on:
Blocks:
 
Reported: 2013-09-12 12:39 UTC by bearophile_hugs
Modified: 2024-12-13 18:11 UTC (History)
0 users

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description bearophile_hugs 2013-09-12 12:39:34 UTC
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.
Comment 1 dlangBugzillaToGithub 2024-12-13 18:11:24 UTC
THIS ISSUE HAS BEEN MOVED TO GITHUB

https://github.com/dlang/dmd/issues/18668

DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB