Array as an argument, ambiguous behaviour.
Cooler
kulkin at hotbox.ru
Thu Jan 30 05:42:51 PST 2014
On Thursday, 30 January 2014 at 12:47:56 UTC, Dicebot wrote:
> On Wednesday, 29 January 2014 at 14:34:54 UTC, Cooler wrote:
>> Here is ambiguity.
>> void fun3(int[] x){ x ~= 5; ... }
>> auto a = new int[10];
>> fun3(a); // Here content of "a" may be changed or may be not
>> changed. Depends on the buffer size that system will allocate
>> for "a" array.
>
> You use very subjective meaning for "ambiguity", one that is
> never normally used in programming language context. Normally
> term "ambiguity" is applied only when _compiler_ can't reliably
> decide meaning of the code snippet and needs to resort to
> special casing.
>
> You are correct in notion that you can't make any reasonable
> judgement yourself about content of a after `fun3` call but
> same applies to `fun2` - it can be or not be modified. It is
> expected - to express all semantics of function body in
> function signature one would have needed to make it of
> comparable length and complexity.
If I use fun2() I expect that fun2() will change the content of
my array, and all changes I will see. If I don't want any change
to my array, I will use fun1(). What should I want to use fun3()?
As many people writes to me in the post - "You may want that
fun3() change content of an array, but can't change length of
array". I cannot imagine such use case.
void fun3(int[] x){ x[0] = 5; x ~= 6; writeln(x); } // What
caller will get?
auto a = new int[10];
fun3(a); // What I must want here to call fun3(). If I want
fun3() will change my array, I should prefer fun2() variant which
will guarantee me that I will get all changes. If i just want
send array to fun() for it internal use I should prefer fun1().
If I call fun3() the contents of array after the call is not
predictable - it can be changed or may not. What must push me to
use fun3()?
>
> In practice you need always to assume the worst - everything is
> modified and nothing can be trusted unless explicitly qualified
> other way around.
In practice if function declared as fun(in int[] a){} I can be
sure that call fun(x) will not change 'x', until the compiler has
a bug, or fun() author don't play with c-like pointers.
More information about the Digitalmars-d-learn
mailing list