On Sunday, March 18, 2018 14:56:04 Steven Schveighoffer via Digitalmars-d wrote: > On 3/18/18 2:24 PM, Jonathan M Davis wrote: > > On Sunday, March 18, 2018 13:10:28 Steven Schveighoffer via > > Digitalmars-d > > > > wrote: > >> On 3/18/18 4:34 AM, sdvcn wrote: > >>> dchar v11=dchar.max; > >>> > >>> auto vp11 = [v11]; > >>> > >>> auto v2 = cast(ubyte[]) (vp11); //v2.length=4 > >>> auto v22 = cast(ubyte[])( [v11]); //v2.length=1 > >> > >> This seems like a bug to me. > >> > >> It appears that v22 has truncated v11 to a byte and made only a single > >> byte array out of it. > > > > Except that that's precisely how you usually get an array any integral > > type smaller than an integer. e.g. > > > > auto arr = cast(ubyte[])([1, 2, 3, 4]); > > > > In this case, you could do > > > > ubyte[] arr = [1, 2, 3, 4]; > > > > instead, but if you're not dealing with an initializaton or assignment > > like this (e.g. you're passing the array to a functon), then the cast > > is the way you do it. Normally, you do it with integer literals, and I > > could see an argument that it shouldn't allow it without VRP being used > > to make it work, but it _is_ a cast, and casts are a bit of a blunt > > instrument. > > > > So, I really don't think that it's a bug. > > It's quite possible that you aren't understanding what is happening: > > ubyte[] arr = cast(ubyte[])[555]; > writeln(arr); // [43] > > Why is this not a bug? I didn't cast the 555 to a ubyte, so it should > either complain that it can't do it, or give me an array of 4 bytes. > > I guess it could be explained as the same thing as: > > ubyte[] arr = [cast(ubyte)555]; > > But this is surprisingly weird behavior.
That's exactly what it's doing, and when you have multiple elements in the literal, it quickly gets a lot more pleasant than casting each element individually. e.g. cast(ubyte[])[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] vs [cast(ubyte)0, cast(ubyte)1, cast(ubyte)2, cast(ubyte)3, cast(ubyte)4, cast(ubyte)5, cast(ubyte)6, cast(ubyte)7, cast(ubyte)8, cast(ubyte)9, cast(ubyte)10] I use this trick all the time when creating arrays of integral types smaller than int, precisely because casting each element is a royal pain and way harder to read. - Jonathan M Davis
