Array as an argument, ambiguous behaviour.

Cooler kulkin at hotbox.ru
Thu Jan 30 08:48:50 PST 2014


On Thursday, 30 January 2014 at 16:18:33 UTC, Steven 
Schveighoffer wrote:
> On Thu, 30 Jan 2014 11:04:44 -0500, Cooler <kulkin at hotbox.ru> 
> wrote:
>
>> On Thursday, 30 January 2014 at 16:01:32 UTC, Cooler wrote:
>>> On Thursday, 30 January 2014 at 15:59:48 UTC, Cooler wrote:
>>>> On Thursday, 30 January 2014 at 15:51:44 UTC, Tobias 
>>>> Pankrath wrote:
>>>>> On Thursday, 30 January 2014 at 15:49:35 UTC, Cooler wrote:
>>>>>>>> I agree. I just want that the case can be expressed in 
>>>>>>>> language syntax more obvious - something like "fun(int[] 
>>>>>>>> const x){}" to emphasize that I understand that fun() 
>>>>>>>> can change content of array, and cannot change the 
>>>>>>>> {pointer,size} pair.
>>>>>>>
>>>>>>> That's what fun(int[] x) does :)
>>>>>>>
>>>>>>> -Steve
>>>>>>
>>>>>> Again...
>>>>>> void fun(int[] x){ x ~= 5; }
>>>>>> auto a = new int[10];
>>>>>> fun(a); // Can you predict the content of 'a'?
>>>>>
>>>>>
>>>>> It's [0, 0, 0, 0, 0, 0, 0, 0, 0, 0].
>>>>
>>>> No!!! It depends how runtime allocates memory for the array. 
>>>> Read http://dlang.org/d-array-article.html.
>>>> If 'a' has internal space enough to place '5' the caller 
>>>> will see
>>>> [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5].
>>>
>>> Sorry!!! My mistake. The caller will see [0, 0, 0, 0, 0, 0, 
>>> 0, 0, 0, 0] :)
>>
>> But that is the proof. The intention of fun() implementer will 
>> not be achieved. And such misunderstanding will appear only at 
>> runtime.
>
> void foo(int x)
> {
>    x = 5;
> }
>
> "hey, why doesn't that work! Setting a parameter to another 
> value should be illegal!"
>
> -Steve

Please understand - I am not against void foo(int[] x){}
I am for predictability of behavior. You suggest to describe 
function's behavior in documentation - quotation from your 
article "It is a good idea to note in the documentation how the 
passed in slice might or might not be
overwritten." My idea is that all potential errors must be 
detected as soon as possible. The D principle - "The program 
compile and runs as expected, or not compile at all".
If you really need to call function that can change content of an 
array, but cannot change size of an array the language syntax 
should allow express it in function signature. I consider "void 
fun(int[] const x){}" more error prone than "void fun(int[] x){}" 
and for the caller and for implemeter.

> I see very little value in that. We don't need to obliterate a 
> tremendous  amount of slice usage (not mentioning how much code 
> will have to be  updated) in order to help newbies understand 
> how slices work.
Any idea can be rejected by this sentence.


More information about the Digitalmars-d-learn mailing list