+= on associative arrays leads to surprising result

berni someone at somewhere.com
Tue Aug 27 16:12:07 UTC 2019

> import std.stdio;
> void main()
> {
>     real[int] a;
>     a[0] += 100;
>     writeln(a);
> }

results (independed of the used compiler) in

> [0:100]

I was a little bit surprised, because a[0] += 100 should be the 
same as a[0] = a[0]+100, which leads to a range violation error. 
Furthermore, as we work with real, I'd expected the result to be 

Is this a bug? I ask, because it would be quite convenient to use 
it the way it works now.

An alternative I found, would be to use object.update. But there 
I've to declare the 100 twice which results in code duplication:

> a.update(0,()=>100.0L,(ref real v)=>v+100.0L);

Hence, my best solution needs two lines:

> if (0 !in a) a[0] = 0;
> a[0] += 100;

What's your oppinion on this?

More information about the Digitalmars-d-learn mailing list