When are associative arrays meant to throw a RangeError?

Ben Davis entheh at cantab.net
Sat Feb 18 11:10:38 PST 2012


On 18/02/2012 13:22, Daniel Murphy wrote:
> "Ben Davis"<entheh at cantab.net>  wrote in message
> news:jho2mf$2a1t$1 at digitalmars.com...
>> Starting with magic initialisation then...
>>
>
> I meant a different magic initialization:
> int[int] aa = null;
> aa[3] = 7; // aa is magically not null any more
>
>> Is it vital that e[nonexistentKey] throw a RangeError, or could it just
>> always return the type's default value if the key is absent?
>>
> This is what it does.

It throws a RangeError. See the examples in my first message in this 
thread. I'm asking if changing the semantics to NOT throw a RangeError 
would be an option.

>> If you change that, then you can make assignment evaluate the RHS fully
>> before even creating the LHS entry, and you won't in the process break the
>> common case where people want to go
>>
>> count[key]++;
>> or
>> array[key]~=element;
>>
>> without worrying about whether it's the first time for that key or not.
>>
>
> This problem is just a bug in code generation from what I can tell, because
> lowering it manually results in the rhs being evaluated first.
>
> import std.stdio;
>
> int* getp()
> {
>      writeln("1");
>      return new int;
> }
>
> void main()
> {
>      *getp() += { writeln("2"); return 1; }();
> }
>
> prints:
> 2
> 1
>
> I have no idea where this is happening in the compiler.

Interesting - my gut feeling is that associative arrays are syntactic 
sugar and are being rewritten to use other constructs, and that 
rewriting is implementing a different execution order.


More information about the Digitalmars-d mailing list