Chaos_99
Chaos_99

Reputation: 2304

Are nested calls to [] operator evaluated left-to-right?

I'm using a library with custom data types that overload the [] operator to allow array-like access to data called MType.

I've created an actual array of these objects like so: MType mtypearray[3];

Now when accessing data, I'm unsure which index is used for what.

mtypearray[a][b] = 5;

Is a the index into the custom MType using the []-overload or into the usual size 3 array declared in MType mtypearray[3];?

My experiments indicate that a is actually the array index and b is used for the custom type index. But this seems so counter-intuitive to the way you usually handle multi-dimensional arrays.

Are []s really evaluated left-to-right instead of right-to-left?

Upvotes: 2

Views: 97

Answers (2)

Peter - Reinstate Monica
Peter - Reinstate Monica

Reputation: 16016

Yes, the indexing operator is left-associative. This is almost counter-intuitive when it comes to declarations. Say, you have an array with 3 elements:

int arr1D[3];

and now want to have 5 of those, again in an array. Naively one would think that

int arr2D[3][5]

would do, but that actually declares 3 one-dimensional arrays of 5 elements each because the left index will be evaluated first. For many purposes this won't matter, as long as the program uses the indices correspondingly. It's 15 ints, contiguous in memory, after all. But the correct, somewhat unintuitive method is to add additional dimensions on the "inside":

int arr2D[5][3]

This associativity is consistent with the general intuitive rule that associativity is inside-out from the perspective of an identifier to which the operators are being applied. Prefix operators are right-associative:

*(&(*a)))

While postfix operators are left-associative.

( (a()) () ) ()

Any other order would probably be surprising.

Upvotes: 1

cadaniluk
cadaniluk

Reputation: 15229

The left square brackets are indeed evaluated first.

mtypearray[a] returns a MType&. mtypearray[a][b] additionally applies the subscript operator to the MType&. So, your assignment is equivalent to

MType& m = mtypearray[a];
m[b] = 5;

Upvotes: 5

Related Questions