Passing an in parameter and aliasing

Jarrett Billingsley kb3ctd2 at yahoo.com
Wed May 23 13:52:55 PDT 2007


"renoX" <renosky at free.fr> wrote in message 
news:f328ns$1f1q$1 at digitalmars.com...
> I'm not sure whether to post this in D.learn or not, but here's my issue:
>
> What happens when you have a function f(in T array[], inout T x)
> and that x is in fact an element of the array?
>
> AFAIK, there are three possibilities:
> 1- the compiler detect the incompatibility and complain, that's nice for 
> the programmer but real hard work for the compiler and it's impossible to 
> catch all the problems for the compiler.
>
> 2- the array is modified when x is modified, which can leads to bug 
> depending on the compiler and its optimization level: hopefully this would 
> be a rare bug, but very hard to catch.
> And if parameter passing is by default as constants, then maybe the bug 
> won't be so rare.
>
> 3- the array is copied which reduce performance is this is done by 
> default.
>
> So which way is-it supposed to be?
>

It works like 2 right now.  3 is just impractical for most cases.  1 can be 
put in manually:

void func(int[] a, ref int x)
in
{
    assert(&x < a.ptr || &x >= (a.ptr + a.length), "x can't be a member of 
a");
}
body
{
    x = 5;
    writefln(a);
    fflush(stdout); // without this, the assertion confusingly gets printed 
first
}

void main()
{
    int[] a = ([1, 2, 3]).dup;
    int x = 0;

    func(a, x);
    func(a, a[0]);
}

You could probably wrap that ugly expression into a mixin or something. 





More information about the Digitalmars-d mailing list