www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Initializing values in associative arrays

reply Joseph Rushton Wakeling <joseph.wakeling webdrake.net> writes:
How safe is it to rely on doing something like this:

     uint[size_t] x;

     foreach(i; iota(0, 10))
         x[i]++;

     foreach(i; iota(5, 15))
         x[i]++;

... ?  In this case "correct" output comes out -- that is, values for keys 1-4 
and 10-14 come out as 1, values for keys 5-9 come out as 2 -- but it seems a
bit 
shaky to assume that just incrementing x[i] without first checking ((i in x)
!is 
null) will come out correctly.

I note that the above works even if uint[size_t] is changed to real[size_t], 
which is a surprise, because I'd have assumed that everything would come out as 
nan's.
Nov 29 2012
parent "bearophile" <bearophileHUGS lycos.com> writes:
Joseph Rushton Wakeling:

 How safe is it to rely on doing something like this:

     uint[size_t] x;

     foreach(i; iota(0, 10))
         x[i]++;

     foreach(i; iota(5, 15))
         x[i]++;

This is part of the D associative array specs, so in theory it's safe, but you have to keep this implementation bug in account: http://d.puremagic.com/issues/show_bug.cgi?id=3825
 I note that the above works even if uint[size_t] is changed to 
 real[size_t], which is a surprise, because I'd have assumed 
 that everything would come out as nan's.

This is a known AA bug :-( I think that there is not yet a patch to fix it. Bye, bearophile
Nov 29 2012