Multidimensional array

Ali Çehreli acehreli at yahoo.com
Thu Jul 4 18:53:22 PDT 2013


On 07/04/2013 06:43 PM, bearophile wrote:

 > Ali Çehreli:
 >
 >> However, that is a confusing syntax because the right-hand side is not
 >> the same type as the elements, which is dchar[3]. Perhaps D supports
 >> it for C compatibility?
 >>
 >> It doesn't match the following. Here, the right-hand side is the same
 >> as the element type:
 >>
 >>     int[2] arr2 = 42;
 >>     assert(arr2 == [ 42, 42 ]);
 >>
 >> But this doesn't compile:
 >>
 >>     char[3][5] arr = [ '.', '.', '.' ];
 >>
 >> Error: mismatched array lengths, 15 and 3
 >>
 >> I see that as a bug but can't be sure.
 >
 > In D char literals as 'x' or even string literals as "xx" are seen as
 > instances of all the types of strings and chars, it's not a bug, it's a
 > feature:
 >
 > void main() {
 >      char x1  = 'x';
 >      wchar x2 = 'x';
 >      dchar x3 = 'x';
 >      string s1  = "xx";
 >      wstring s2 = "xx";
 >      dstring s3 = "xx";
 > }
 >
 >
 > There is a way to specify the type of a string, so this gives errors:
 >
 > void main() {
 >      string s1  = "xx"d;
 >      string s2  = "xx"w;
 >      wstring s3 = "xx"d;
 > }
 >
 > Bye,
 > bearophile

Thanks for the refresher. My comment was about array initialization. We 
can define an array by a value on the right-hand side that is the same 
as the element types:

     int[2] arr2 = 42;
     assert(arr2 == [ 42, 42 ]);

Good: Every element has the value 42.

Now I have another array where the elements are of type int[3]:

     int[3][2] arr = [ 10, 20, 30 ];

Error: mismatched array lengths, 6 and 3

Do you see the inconsistency? The element type is int[3] and the initial 
value is [ 10, 20, 30 ]. However there is a compilation error.

Further, the code compiles even if I use a different type as the initial 
value:

     int[3][2] arr = 10;

I would expect that to be an error because the element type is not an 
int but int[3]. We know that an int[3] can be initialized by 10 but a 10 
should not be allowed to be used as an int[3].

That was my point.

Ali



More information about the Digitalmars-d-learn mailing list