www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Is this a bug? Initializing immutable fixed size arrays

reply Shachar Shemesh <shachar weka.io> writes:
The following compiles fine:
immutable char[5] array = x"01 02 03 04 05";

The following doesn't:
immutable ubyte[5] array = x"01 02 03 04 05";

which makes sense, but neither does:
immutable ubyte[5] array = cast(immutable ubyte []) x"01 02 03 04 05";

playground.d(1): Error: cannot implicitly convert expression 
("\x01\x02\x03\x04\x05") of type immutable(ubyte[]) to immutable(ubyte[5])

Just to make sure we're clear, the following (no op) cast still compiles:
immutable char[5] array = cast(immutable char []) x"01 02 03 04 05";


To summarize: An immutable(char[]) is a valid initializer for an 
immutable(char[5]), but an immutable(ubyte[]) is not a valid initializer 
for an immutable(ubyte[5]).

Why?

Just in case anyone is going to claim that the cast to another type 
destroys the compiler's understanding of what this is, the following works:

immutable char[5] array = cast(immutable (char[]))(cast(immutable 
ubyte[]) x"0102030405");

All examples with dmd 2.072.1

Shachar
Dec 11 2016
parent Bauss <jj_1337 live.dk> writes:
On Monday, 12 December 2016 at 06:43:52 UTC, Shachar Shemesh 
wrote:
 The following compiles fine:
 immutable char[5] array = x"01 02 03 04 05";

 [...]
This doesn't seem like a bug:
 immutable ubyte[5] array = x"01 02 03 04 05";
This however does:
 immutable ubyte[5] array = cast(immutable ubyte []) x"01 02 03 
 04 05";
There's a workaround for this though. immutable ubyte[5] array = cast(immutable(ubyte[5]))x"01 02 03 04 05";
Dec 12 2016