Bug 12032 – One case of refused slicing assignment to fixed size array

Status
RESOLVED
Resolution
INVALID
Severity
normal
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
x86
OS
Windows
Creation time
2014-01-29T08:31:21Z
Last change time
2022-08-22T11:31:59Z
Keywords
rejects-valid
Assigned to
No Owner
Creator
bearophile_hugs

Comments

Comment #0 by bearophile_hugs — 2014-01-29T08:31:21Z
With dmd 2.065beta this compiles and runs with no errors: int[2] foo() { int[] a = [1, 2, 3, 4]; return a[0 .. 2]; // OK } void main() {} This compies and runs with no errors: void main() { int[] a = [1, 2, 3, 4]; int[2] b; b[] = a[$ - 2 .. $]; // OK } While this code: int[2] foo() { int[] a = [1, 2, 3, 4]; return a[$ - 2 .. $]; // Error } void main() {} Gives: test.d(3): Error: cannot implicitly convert expression (a[__dollar - 2u..__dollar]) of type int[] to int[2] I'd like this code to compile.
Comment #1 by razvan.nitu1305 — 2022-08-22T11:31:59Z
This issue is invalid. The first case compiles because the compiler is able to deduce that the returned array is of size 2 (the range bounds are literal and therefore known at compile time). The second case is an assignment of slices, therefore the error (if any) can only be caught at runtime. In the third case, the length of the `a` array cannot be known because `a` is a dynamic array and any number of elements could be added or deleted from a before we return the slice. Therefore the compiler rejects it. If a would have been a static array, then the compiler would have accepted the code because it can statically determine that the returned array matches the expected size.