D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 12032 - One case of refused slicing assignment to fixed size array
Summary: One case of refused slicing assignment to fixed size array
Status: RESOLVED INVALID
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: x86 Windows
: P2 normal
Assignee: No Owner
URL:
Keywords: rejects-valid
Depends on:
Blocks:
 
Reported: 2014-01-29 08:31 UTC by bearophile_hugs
Modified: 2022-08-22 11:31 UTC (History)
1 user (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description bearophile_hugs 2014-01-29 08:31:21 UTC
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 RazvanN 2022-08-22 11:31:59 UTC
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.