Bug 1262 – Local variable of struct type initialized by literal resets when compared to .init
Status
RESOLVED
Resolution
FIXED
Severity
normal
Priority
P2
Component
dmd
Product
D
Version
D1 (retired)
Platform
x86
OS
Linux
Creation time
2007-06-08T07:03:00Z
Last change time
2014-02-16T15:23:53Z
Keywords
wrong-code
Assigned to
bugzilla
Creator
fvbommel
Comments
Comment #0 by fvbommel — 2007-06-08T07:03:32Z
(First seen in a message posted by "HATA" to d.D.bugs, http://www.digitalmars.com/webnews/newsgroups.php?art_group=digitalmars.D.bugs&article_id=11355)
---
import std.stdio;
struct A { int v; }
void main() {
A a = A(10);
writefln("Before test 1: ", a.v);
if (a == a.init) writefln(a.v,"(a==a.init)");
else writefln(a.v,"(a!=a.init)");
a.v = 100;
writefln("Before test 2: ", a.v);
if (a == a.init) writefln(a.v,"(a==a.init)");
else writefln(a.v,"(a!=a.init)");
a = A(1000);
writefln("Before test 3: ", a.v);
if (a == a.init) writefln(a.v,"(a==a.init)");
else writefln(a.v,"(a!=a.init)");
}
---
Even though the value of a.v is not 10 before the last two if statements, it gets set to 10 right before the test.
This doesn't happen if 'a' is a global variable, or if a static opCall(int) with traditional implementation is added. So this is a workaround:
---
struct A {
int v;
static A opCall(int x) {
A result;
result.v = x;
return result;
}
}
---
Comment #1 by davidl — 2007-06-12T11:10:30Z
umm, struct literals should not be l-value
Comment #2 by fvbommel — 2007-06-12T12:13:51Z
(In reply to comment #1)
> umm, struct literals should not be l-value
And your point is?
At no point in the code is a struct literal used as an l-value. There's a struct variable initialized _by_ a struct literal, and a struct literal being assigned to a variable, but those are the only struct literals used. And those operations should only copy the value of the struct literal to the variable being initialized, which should be perfectly fine.
Structs are value types, not reference types.
Comment #3 by davidl — 2007-06-12T20:55:55Z
heh, you are right. Literal things screw up in my mind