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
LVL 2
yairyAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
MotazConnect With a Mentor Commented:
If you declare the array argument such as :

function Text(X: list): Integer;

the array will be copied to function's stack, if you are not sure, you can send more than 16 k byte array, stack overfollow error will occure when you call this function, so that even if you want to read the list only it is best to use reference declaration such as:

function Test(var X: List): Integer;

because it is more save when using large size array and it will consume less stack memory.

Azzoz

www.geocities.com/motaz1
0
 
yairyAuthor Commented:
Edited text of question.
0
 
KennyIT Application ExecutiveCommented:
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.
0
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

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

Yair
0
 
VEngineerCommented:
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?

0
 
MotazCommented:
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
0
 
yairyAuthor Commented:
Thank you all,
Motaz - I visited your site, nice.

Yair

0
All Courses

From novice to tech pro — start learning today.