On Sun, 03 Jan 2010 05:56:21 +0300, Steven Schveighoffer <[email protected]> wrote:

On Sat, 02 Jan 2010 20:54:30 -0500, Denis Koroskin <[email protected]> wrote:

On Sun, 03 Jan 2010 04:23:00 +0300, Trass3r <[email protected]> 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

Array casting is something I avoid as a plague. It is highly inconsistent: in some cases, it does bitwise casting (kind of a reinterpret_cast, changing size of an array), in others - in creates per-element copy of an array, thus doing at runtime something I'd like to be done at compile-time.

Maybe it's just me, but I wouldn't recommend anyone using array casting (other that T[] -> void[]).

Reply via email to