Sign in Join

Live chat for Free Pascal, Lazarus, Delphi and every Pascal programmer.

Mailing lists / fpc-pascal / 2010-04

var parameter

2 messages · 2 people ·

Reply by email Subscribe to this list Your subscription

Read-only archive. Use j and k to move between messages.

spir ☣

Hello,

I wrote a little simulation prog to try and understand better the semantics of var parameters (see below code and output).

It seems they behave like if passed via pointers, but also locally _operated_ via pointers. Meaning there is in ChangeVar no real local variable n (on the stack). But instead Pascal silently behaves like if using p^ for both getting and setting the variable ('s value) "on-place". This is illustrated by the difference of result between the simulating funcs changePtrVar & changePtrDirect.

Is this interpretation more or less correct?
How are var parameters actually implemented?

Maybe there is still a local var, but the behaviour rather looks like the following code:

procedure change(p:IntPointer);
var
	n : Integer;
begin
	n := p^;	// <=> var parameter passing
	p^ := n+1;	// <=> n := n+1   but:
			// setting silently reuses p
end;
======= code =======
var
	n,m : Integer;
	p : IntPointer;
procedure changeVar(var n:Integer);
begin
	n := n+1;
end;
procedure changePtrVar(p:IntPointer);
var
	n : Integer;
begin
	n := p^;
	n := n+1;
end;
procedure changePtrDirect(p:IntPointer);
begin
	p^ := p^+1;
end;
begin
	// change var
	n := 3;
	changeVar(n);
	writeln(n);
	// change ptr var
	n := 3;
	p := @n;
	changePtrVar(p);
	writeln(n);
	// change ptr direct
	n := 3;
	p := @n;
	changePtrDirect(p);
	writeln(n);
end.
======================
======= output =======
4
3
4
======================

Denis

PS: Is there a reason why I don't receive my own posts? (this only happens to me on fpc and lazarus mailing lists). ________________________________

vit esse estrany ☣

spir.wikidot.com

cobines
to spir ☣

2010/4/30 spir ☣ :

Show quoted text 9 lines
Hello, I wrote a little simulation prog to try and understand better the semantics of var parameters (see below code and output). It seems they behave like if passed via pointers, but also locally _operated_ via pointers. Meaning there is in ChangeVar no real local variable n (on the stack). But instead Pascal silently behaves like if using p^ for both getting and setting the variable ('s value) "on-place". This is illustrated by the difference of result between the simulating funcs changePtrVar & changePtrDirect. Is this interpretation more or less correct? How are var parameters actually implemented?

Yes, var parameters are passed by reference (pointer). See here Variable Parameters:
http://www.freepascal.org/docs-html/ref/refse59.html.

cobines