what's the difference between ref and inout in D2?
bearophile
bearophileHUGS at lycos.com
Fri Mar 12 13:56:26 PST 2010
Trass3r:
> why do we have "in" if all
> parameters are in by default?
If you start performing some experiments on your own you can write a small program like this:
// program1
import std.stdio: writeln;
void foo(int x, in int y) {
x = 1;
y = 2;
}
void main() {
int x, y;
foo(x, y);
writeln(x, " ", y);
}
The compiler prints an error because y is seen as const. So a better question (I don't know the answer) is: what's the purpose of "in" if now function arguments can be const?
A related program:
// program2
import std.stdio: writeln;
void bar(out int x) {
int y = x; // line 4
writeln(y); // prints 0
}
void main() {
int x = 10;
bar(x);
writeln(x); // prints 0
}
Is this program correct? It compiles and runs, printing 0 two times. I don't like that code. I think it's even worse than a similar C program, where the caller must add a &x, revealing part of how x will be used by the bar() function.
I think that in theory the line 4 is an error, because technically y is an output variable, so it's not initialized yet. In practice it's initialized with its init. And I think code like that program2 can easily hide bugs. This shows why built-in tuples are good. Currently there are many holes in D2.
If you have answers or comments please let us know.
Bye,
bearophile
More information about the Digitalmars-d-learn
mailing list