Link to home
Start Free TrialLog in
Avatar of yairy
yairy

asked on

By var and by Value

I student asked me a interesting question:

If I am passing an array argument to a function
( function (i:list):integer; )
does it ALWAYS copy the array to
a new location for the new varlible,
EVEN if I am doing only READ operations ?

i.e. Does the compiler "optimize" the code and change it to by var
( function (VAR i:list):integer; )
because its much cheapper to pass a pointer then coping an array ?

The interface is good old TP7...

Anybody knows anything ?

Yair
Avatar of yairy
yairy

ASKER

Edited text of question.
I don't believe it does. I think you need to pass it by reference yourself. I am not so sure, though. Only used TP6.
ASKER CERTIFIED SOLUTION
Avatar of Motaz
Motaz

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of yairy

ASKER

So you mean that ALTHOUGH  I am only
reading the array items, the compiler isn't smart enough to pass it by ref ?

Yair
I haven't done pascal in years, but one way you can test it is:

we have two procedures, the caller and the callee (procedure being called).

In the caller, make a pointer, point it to the array, and print out the address that it is pointing to.

In the callee, make a pointer, point it to the array, and print out the addres that it is pointing to.

If the addresses match, then you can see that it is not a copy.  Otherwise if the addresses are different, they are a copy.

The compiler doesn't have to be "smart."  It depends on the language definition really.  If the language reference manual doesn't say anything about it, then it is up to the choice of the compiler writer.  Who knows if someone really wants to make a copy of an array?  Should they be allowed to do it?

Calling array by reference instead of by copy is not a smart idea, when you want to use calling by reference you have to add var keyword to the parameter, ignoring var keyword means calling by copy.

Motaz
Avatar of yairy

ASKER

Thank you all,
Motaz - I visited your site, nice.

Yair