Passing an in parameter and aliasing

Bill Baxter dnewsgroup at billbaxter.com
Wed May 23 14:06:02 PDT 2007


Jarrett Billingsley wrote:
> "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");
> }

The thing with this is it may catch the error but it doesn't help the 
compiler generate more optimized code.  The C99 'restrict' keyword does, 
though.  I suppose the compiler could be smart enough to deduce 
'restrict' semantics are in effect from the assert message above.  That 
would be pretty neat.

Linky (top google hit for 'C99 restrict keyword'): 
http://www.cellperformance.com/mike_acton/2006/05/demystifying_the_restrict_keyw.html


--bb



More information about the Digitalmars-d mailing list