D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 4907 - Catching more simple out-of-bounds errors at compile-time
Summary: Catching more simple out-of-bounds errors at compile-time
Status: RESOLVED WONTFIX
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: All All
: P4 enhancement
Assignee: No Owner
URL:
Keywords: bootcamp
Depends on:
Blocks:
 
Reported: 2010-09-21 05:07 UTC by bearophile_hugs
Modified: 2023-02-02 11:19 UTC (History)
2 users (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description bearophile_hugs 2010-09-21 05:07:24 UTC
One of the advantages of static typing is that it catches some classes of bugs early, instead of later at runtime. Similarly, catching array out-of-bounds errors early at compile-time is better than catching them at run-time in debug builds.

Catching all cases of out-of-bounds errors at compile time is not possible and it's hard to do, but there are simple cases that are common coding mistakes and probably easy to catch at compile-time:


void main() {
    int[10] arr;
    for (int i = 0; i <= arr.length; i++)
        arr[i] = i;
}


In idiomatic D that kind of bugs is less common because explicitly bounded loops are less common:

void main() {
    int[10] arr;
    foreach (i, ref x; arr)
        x = i;
}


But probably there are enough D programmers that don't use idiomatic D or translate code from Java/C/C++/C# code that contains explicit loops.


Currently DMD is able to spot such out-of-bounds errors at compile-time only if the index is a compile-time constant:


const int i = 6 / 2;
void main() {
    int[3] arr;
    arr[i] = 3; // Error: array index 3 is out of bounds arr[0 .. 3]
}
Comment 1 RazvanN 2023-02-02 11:19:56 UTC
Well, this check amounts to adding a special case in the compiler for no apparent benefit since you end up with an assertion error at runtime anyway.

I don't think this is worth it.