[fpc-pascal] var parameter

spir ☣ denis.spir at gmail.com
Fri Apr 30 11:39:37 CEST 2010


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



More information about the fpc-pascal mailing list