Bug 4907 – Catching more simple out-of-bounds errors at compile-time
Status
RESOLVED
Resolution
WONTFIX
Severity
enhancement
Priority
P4
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2010-09-21T05:07:24Z
Last change time
2023-02-02T11:19:56Z
Keywords
bootcamp
Assigned to
No Owner
Creator
bearophile_hugs
Comments
Comment #0 by bearophile_hugs — 2010-09-21T05:07:24Z
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 by razvan.nitu1305 — 2023-02-02T11:19:56Z
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.