3

Why is multidimensional array declaration order reversed?

As an example, an array of 5 dynamic arrays of uint is uint[][5] (note that the notation is reversed when compared to some other languages).

Which is all the more confusing given that access follows custom:

To access the second uint in the third dynamic array, you use x[2][1] (indices are zero-based and access works in the opposite way of the declaration, i.e. x[2] shaves off one level in the type from the right).

cf. https://solidity.readthedocs.io/en/v0.5.1/types.html#arrays

4

There are two general mindsets about type notation in programming languages.


Declare it like you use it (or: variable-centric)

C and many C-style languages do this.

For example, reading from left to right:

int test[3]; means that you will get an int if on test you access an index less than 3: test[2]

int arr[4][10]; means that you will get an int if on arr you access an index less than 4, and then access an index less than 10: arr[3][9]

As you can see, the type declaration resembles the way you would use it.


Nested notation

Solidity and many other modern languages use this.

With this system, the type is completely separated from the variable name. If you see [4] in a type declaration, the type before the [4] is always the type of the array elements.

For example, reading from right to left:

uint256[3] test; means that test is an array of 3 elements, where each element is a uint256.

uint256[4][10] arr; means that arr is an array of 10 elements, where each element is an array of 4 elements, where each element is a uint256.

When accessing it, the indices you are accessing are reversed because you are 'unpacking' the nested type. For example: arr[9] will be an array of 4 elements.


Both notations have their merits. I personally find nested notation easier to read. Nested notation is often much friendlier towards function pointers, with the disadvantage of the array indices being in opposite order with respect to the array sizes in the type declaration. Also, nested notation is much friendlier towards the mapping data type of Solidity.

There are many forums online full of people debating this. In the end, when designing a language you just have to pick one and stay consistent. There are always going to be programmers coming from one world and getting confused by the notation in the other world.

  • 1
    Kudos for putting all the effort. Nicely written (in particularly, in light of the fact that this question is general and not specific to Ethereum or Solidity). – goodvibration Dec 19 '18 at 16:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.