casting of arrays really needs to be clarified in the specs!

Trass3r un at known.com
Fri Mar 12 06:46:57 PST 2010


The D specs are missing a detailed explanation how array casting works.
(I also found a 2 years old issue about it:  
http://d.puremagic.com/issues/show_bug.cgi?id=2494)

It needs to be clarified when a reinterpret_cast is done and when the  
elements are converted to the new type depending on whether it is an array  
literal, another array expression, an array of structs, classes or  
interfaces AND whether it is a constant array or not.
A sane and consistent solution is required.


The only information at all is hidden deep inside the huge expressions  
documentation:
http://www.digitalmars.com/d/2.0/expression.html#ArrayLiteral

(Also, is this information correct? For example I thought array literals  
are dynamic arrays now ("The AssignExpressions form the elements of a  
static array")?
Additionally: "The type of the first element is taken to be the type of  
all the elements" ->  
http://www.digitalmars.com/d/archives/digitalmars/D/casting_array_literals_doesn_t_work_as_stated_in_the_docs_104333.html#N104334)


We already had several discussions about it here:  
http://www.digitalmars.com/d/archives/digitalmars/D/learn/converting_a_byte_array_to_a_struct_array_18526.html  
followed by  
http://www.digitalmars.com/d/archives/digitalmars/D/casting_array_literals_doesn_t_work_as_stated_in_the_docs_104333.html


RGB[256] PALETTE = cast(RGB[256]) [
     0x00, 0x00, 0x00, 0xE3, 0x53, 0x00,
     0xCF, 0x4B, 0x07, 0xBF, 0x43, 0x0F, ...

doesn't work cause of "non-constant expression"

RGB[256] PALETTE = (cast(RGB[]) [
     0x00, 0x00, 0x00, 0xE3, 0x53, 0x00,
     0xCF, 0x4B, 0x07, 0xBF, 0x43, 0x0F, ...
]) (0 .. 256);

compiles, but yields empty structs (cause it tries to cast each element to  
a struct instance if I'm not mistaken)

RGB[] PALETTE = (cast(RGB*) cast(ubyte[]) [...])[0..256];

makes it work, but of course it's a bit hacky.


Also see:
http://codepad.org/OGjXADdu
and my answer:
http://codepad.org/bvk63OPw



More information about the Digitalmars-d mailing list