What's wrong with this code?
bearophile
bearophileHUGS at lycos.com
Sat Jan 8 13:39:34 PST 2011
Sean Eskapp:
> I had some code that was segfaulting, so I rewrote the basic idea as a
> fibonacci function, and lo and behold, it still segfaults. Why, and how to fix?
Two versions:
struct Fib {
private const Fib* left, right;
this(in Fib* left=null, in Fib* right=null) {
this.left = left;
this.right = right;
}
const int evaluate() {
if (left is null)
return 1;
else
return left.evaluate() + right.evaluate();
}
}
Fib* bar(int n) {
if (n == 0 || n == 1)
return new Fib();
else
return new Fib(bar(n - 1), bar(n - 2));
}
void main() {
auto x = bar(5);
assert(x.evaluate() == 8);
}
--------------------
struct Fib {
private const Fib* left, right;
this(in Fib* left=null, in Fib* right=null) {
this.left = left;
this.right = right;
}
const int evaluate() {
if (left is null)
return 1;
else
return left.evaluate() + right.evaluate();
}
}
Fib* bar(int n) {
if (n == 0 || n == 1)
return new Fib();
else
return new Fib(bar(n - 1), bar(n - 2));
}
void main() {
auto x = bar(5);
assert(x.evaluate() == 8);
}
Bye,
bearophile
More information about the Digitalmars-d-learn
mailing list