On Fri, May 1, 2009 at 10:07 AM, MLT <[email protected]> wrote:

> At first I thought that maybe on my machine int and long have the same 
> length, or some such. But it works, for int, long, and short. And they do 
> have different lengths.

D's integer types are not like C's.  They are fixed size and do not
vary from platform to platform.  See
http://www.digitalmars.com/d/1.0/type.html

> I tried a bit more:
> ---
> typedef long tlong ;
>
> void main()
> {
>        int[] x = [1,2,3,4] ;
>
>        tlong[] y = cast(tlong[])[1,2] ; // <- this works
>
>        Stdout(y).newline ;
>
>        y = cast(tlong[]) x ; // This doesn't
>
>        Stdout(y).newline ;
> }
> ---
> prints out:
> [1, 2]
> [8589934593, 17179869187]
>
> The the initialization works, but casting from int[] to long[] in general 
> doesn't.

You're actually doing two different things there.

Initialization is treated as a special case and casting it will cast
each element.

But array casts done at runtime will do a bit cast - that is, given
your int[] [1, 2, 3, 4], when you cast it to a long[] at runtime, it
takes that chunk of memory, figures out how many longs will fit in it
(in this case 2), and gives you a new array reference to the same data
but with a different type.  Those big weird numbers are
0x00000002_00000001 and 0x00000004_00000003, respectively.  Woah look
at that, 1, 2, 3, 4!

To make it more apparent, try casting an int[] to a byte[] or
something.  You'll see that it then splits up each original int into
four bytes.

Reply via email to