Arrays - why is the [index] operator only one way?


#1

I notice i can do

int val = arrayname[INDEX];

but not

arrayname[INDEX] = val;

( i assume i have to use getReference() = val;
or set( val ) )

but using [] both ways would be so much nicer - like vector<>.
Was there some big reason why this wasnt written in ?.


#2

Well, the preferred way is to use set(), because it handles the case where the index is out-of-bounds…


#3

cool.

But what was the reason for not implementing a [] “setter” instead?


#4

Because it’d have to return a reference, which might be a duff pointer and will crash. If you have a set method, it gets a chance to fail gracefully.