Array construction - why backwards?

Bill Baxter dnewsgroup at billbaxter.com
Mon Apr 14 22:59:57 PDT 2008


Barry Denton wrote:
> The following is from the Tango book
> 
> // C-style, or postfix, declarations
> int x[3];          // Declares an array of 3 ints
> int x[3][5];       // Declares 3 arrays of 5 ints
> int (*x[5])[3]; // Declares an array of 5 pointers to arrays of 3 ints
>     The preferred syntax is called prefix syntax.
> // D-style, or prefix, declarations
> int[3] x;          // Declares an array of 3 ints
> int[3][5] x;       // Declares 5 arrays of 3 ints
> int[3]*[5] x;      // Declares 5 pointers to arrays of 3 ints
>     The syntactical differences between the two styles are obvious, but prefix
> multidimensional array declarations can be confusing to those with a C background. You値l
> notice that the order is reversed from the postfix declarations. However, indexing values
> from the multidimensional arrays is done in the same way, no matter how they are declared,
> as in the following example.
> int x[5][3];      // Postfix declaration of 5 arrays of 3 ints
> int[3][5] y;      // Prefix declaration of 5 arrays of 3 ints
> x[0][2] = 1;      // The third element of the first array is set to 1.
> y[0][2] = 2;      // the third element of the first array is set to 2.
>     As you can see, postfix and prefix come into play only in array declarations. You index
> them both in the same way.
> 
> 
> I do not know any other language that does this backwards declaration -postfix.
> 
> Can someone tell me why that was needed? It is confusing

It makes declarations more consistent that way.

T[5]  is a type that means array of 5 T's.

If T is an int that means you have an int[5].

Now what if T is an int[3]?

Isn't it logical that to make an array of 5 of those you would do:
T[5] ==> (int[3])[5] ==> int[3][5]

Unfortunately the designers of C thought that for indexing, the last
index should vary the fastest.  That means indexing has to be in
backwards order from declaration of size, because D tries to be as
similar to C syntax as possible.

--bb


More information about the Digitalmars-d-learn mailing list