Array as an argument, ambiguous behaviour.

Steven Schveighoffer schveiguy at yahoo.com
Thu Jan 30 08:15:02 PST 2014


On Thu, 30 Jan 2014 10:49:34 -0500, Cooler <kulkin at hotbox.ru> wrote:

> On Thursday, 30 January 2014 at 15:29:50 UTC, Steven Schveighoffer wrote:
>> On Thu, 30 Jan 2014 10:24:14 -0500, Cooler <kulkin at hotbox.ru> wrote:
>>
>>> On Thursday, 30 January 2014 at 14:40:36 UTC, Dicebot 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'?

I suspect you mean:

void fun(int[] x) {x.length += 1; x[0] = 5;}

I cannot predict what the caller will see. But this is not a problem of  
*signatures*. The caller will not see ANY changes to {pointer,size} pair  
of x. That is the point -- it's passed by value.

Note that this implementation is completely predictable:

void fun(int[] x) {x[0] = 5; x.length += 1;}

I want to stress that just because you can find an implementation that has  
a bug doesn't mean that there is an opportunity for the compiler to detect  
that bug, especially a logic bug. The compiler simply cannot know what you  
are thinking.

> In your case:
> void fun(int[] x){ x = [1, 2]; } // Compilation ok. Implementation's  
> error.
> The fun() implementer made error and think that caller will get new  
> array. But it will get it only at runtime!
> If we for example (just for example) have
> void fun(int[] const x){ x = [1, 2]; } // Compilation error.

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.

-Steve


More information about the Digitalmars-d-learn mailing list