Bug 3825 – (D1 only) AAs entries are default initialized before the new value is evaluated
Status
RESOLVED
Resolution
WONTFIX
Severity
major
Priority
P2
Component
dmd
Product
D
Version
D1 (retired)
Platform
All
OS
All
Creation time
2010-02-18T12:26:51Z
Last change time
2019-11-06T14:48:09Z
Keywords
pull, wrong-code
Assigned to
No Owner
Creator
bearophile_hugs
Comments
Comment #0 by bearophile_hugs — 2010-02-18T12:26:51Z
import std.stdio;
void main() {
string[] words = ["how", "are", "you", "are"];
int[string] aa1;
foreach (w; words)
aa1[w] = ((w in aa1) ? (aa1[w] + 1) : 2);
writeln(aa1); // Prints: [how:1,you:1,are:2]
int[string] aa2;
foreach (w; words)
if (w in aa2)
aa2[w]++;
else
aa2[w] = 2;
writeln(aa2); // Prints: [how:2,you:2,are:3]
}
This can be a source of bugs in programs. I don't know if there are ways to help the programmer avoid this bug.
Comment #1 by yebblies — 2012-02-02T23:35:00Z
*** Issue 5021 has been marked as a duplicate of this issue. ***
Comment #2 by issues.dlang — 2012-05-09T00:21:06Z
*** Issue 8070 has been marked as a duplicate of this issue. ***
Comment #3 by bearophile_hugs — 2012-06-21T00:10:43Z
Yesterday I've wasted some hours to locate this problem again in one of my programs. I hope this bug will be fixed.
Comment #4 by yebblies — 2012-10-29T06:26:23Z
*** Issue 7914 has been marked as a duplicate of this issue. ***
Comment #6 by bearophile_hugs — 2013-01-12T08:58:03Z
Hara, I am reading the discussions in Pull 1465, and I have to say I use this kind of code all the time:
aa[x]++;
It's very handy. It's similar to a Python defaultdict:
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> x = 'c'
>>> d[x] += 1
>>> d
defaultdict(<type 'int'>, {'a': 1})
If you disallow that If you disallow that, I will have tons of broken code. And I have to replace:
aa[x]++;
With:
if (x in aa)
aa[x]++;
else
a[x] = 0;
This makes D code longer, and it doesn't make it safer.
Comment #7 by github-bugzilla — 2013-03-03T17:46:25Z