casting array literals doesn't work as stated in the docs
Steven Schveighoffer
schveiguy at yahoo.com
Sat Jan 2 18:56:21 PST 2010
On Sat, 02 Jan 2010 20:54:30 -0500, Denis Koroskin <2korden at gmail.com>
wrote:
> On Sun, 03 Jan 2010 04:23:00 +0300, Trass3r <mrmocool at gmx.de> wrote:
>
>> http://www.digitalmars.com/d/2.0/expression.html#ArrayLiteral
>>
>> The code example from the docs yields [1 1] and [1 0 1 0] instead of [1
>> 1] and [257] for dmd 2.037.
>>
>>
>> Additionally
>>
>> short[] t = [cast(short) 5, 3];
>> short[] t2 = [cast(short) 5, 3].dup;
>>
>> void main()
>> { ...
>>
>> yields:
>>
>> Error: cannot evaluate _adDupT((& D12TypeInfo_G2i6__initZ),[5,3]) at
>> compile-time
>> Error: cannot implicitly convert expression (_adDupT((&
>> D12TypeInfo_G2i6__initZ),[5,3])) of type int[] to short[]
>> Error: cannot evaluate _adDupT((& D12TypeInfo_G2i6__initZ),[5,3]) at
>> compile-time
>>
>>
>> Using int instead of short only removes the second message.
>>
>>
>> Compiler bug(s)?
>
> Yes and no. It used to work (and should still work), but the behavior
> was changed to take all array literal values into consideration.
>
> "Proper" code should look like this:
>
> short[] t = [cast(short) 5, cast(short)3];
>
> which is err... I'll let someone else to decide. Just imagine there are
> ten (or more) values in an array literal.
the cast-entire-array takes care of that. Corrected docs example:
short[] rt = cast(short[]) (cast(byte[])[1, 1]).dup;
Note the cast of the entire literal, not just the first element.
so now, if you want to set the type of the array, cast the entire array.
If you want to set the type of only one element, cast that one element,
but the runtime might decide to use a bigger type anyways.
correcting your code:
short[] t = cast(short[])[5,3];
short[] t2 = cast(short[])[5,3].dup;
-Steve
More information about the Digitalmars-d
mailing list