inout/out static array parameter

Regan Heath regan at netwin.co.nz
Tue Feb 21 20:16:30 PST 2006


On Wed, 22 Feb 2006 14:15:32 +1100, Derek Parnell <derek at psych.ward> wrote:
> On Wed, 22 Feb 2006 03:02:22 +0000 (UTC), Tom wrote:
>
>> Why is this illegal? Where does the documentation states this?
>> Does it have something to do with the matter that int[10] is allocated  
>> onto the
>> stack? Sometimes I think D losses its abstraction capability when one  
>> has to be
>> concerned about this kind of differences.
>>
>> 5# void f(inout int[10] x)
>> 6# {
>> 7# 	x[0..$] = 99;
>> 8# }
>>
>> test.d(5): cannot have out or inout parameter of type int[10]
>
> I cannot see why D should be upset with this. The implementation would be
> just be passing the address of the int[10] array, just as it does for  
> 'in' parameters.

Not quite, when you pass something as 'in' you always get a copy of it,  
this is true even for arrays. The important thing to realise is exactly  
what it's passing/copying.

In this case:

int[10] data;
void foo(int[10] a) {}
foo(data);

You're passing a pointer to the array data, 'in' copies that pointer and  
passes the copy.

In this case:

int[10] data;
void foo(inout int[10] a) {}
foo(data);

You're not passing a copy of the pointer to the array data, you're passing  
the actual pointer. As we all know static/fixed arrays have a fixed data  
pointer which cannot be assigned to or changed in any way. Therefore it's  
illegal to pass that pointer as 'inout'.

> In conceptual terms, it is identical to this, which D does
> allow ...
>
> struct X
> {
>     int[10] x;
> }
> void f(inout X q)
> {
> 	q.x[0..$] = 99;
> }

I think it depends on what "conceptual" really means in this case, in  
terms of "how it works"(TM) I think it's closer to this:

const int* data;

void foo(inout int* p) {}
void bar(int* p) {}

void main()
{
	bar(data);
	foo(data);
}

which gives: "can only initialize const data inside constructor" for the  
call to "foo".

Note: If you modify p in bar, print the value of data before and after the  
call and initialise it to the address of an int you'll see that 'p' really  
is a copy of 'data'.

Regan



More information about the Digitalmars-d mailing list