Passing an in parameter and aliasing

renoX renosky at free.fr
Fri May 25 09:44:17 PDT 2007


Bill Baxter a écrit :
> 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.

Well, if I understood correctly Jarrett Billingsley's answer, the 
semantic on 'in' is the same as 'restrict': the fastest as the compiler 
will be free to optimize but the most fragile from programmers point of 
view because if you violate the restrict restriction the result is 
unpredictable (no bug, a bug depending on optimization flags, fun!)

Sure, it'd be nice if the compiler was able to do this kind of 
optimization without the in|restrict hint but this is hard.

renoX




More information about the Digitalmars-d mailing list