[comp.sys.mac.programmer] Nested routines as values

bayes@hpislx.HP.COM (Scott Bayes) (04/05/90)

> In <612@fsu.scri.fsu.edu>, pepke@gw.scri.fsu.edu (Eric Pepke) says
> "In Pascal, don't nest procedures to be passed by procedure pointer."
> 
> As a non-THINK-Pascal user (^v^), I have to disagree. I find it a very
> useful technique to nest routines (functions and procedures), and
> to pass pointers to routines of all kinds, nested and unnested.
> 
> Nested routines do expect an extra argument, being the static link.
> Provided you supply this argument, everything works fine.

I think that if you understand the above point and its consequences
clearly, then it's okay.  The problem is that programmers sometimes
don't understand all the consequences.  It's safer to say "don't do
dat."  The feeling is akin to LISP programmers' feelings about side
effects-- avoid when possible.

The static link points to a stack frame, which is an ephemeral quantity.
If you are not currently executing in the statically-scoped parent
procedure of the pointed-to nested routine when you call the pointer,
that frame will not be valid.  Even if you are in the parent procedure,
you should be currently executing in the same invocation as was in
effect when the static link was store.  A scenario for failure follows:

If you store the address of the procedure and its _current_ static link
in globals, exit the statically scoped parent procedure, then call the
pointer later (when the stack frame to which the static link points is
no longer on the stack,) you will be very unhappy indeed.  Any access to
local variables or parameters of the parent will be invalid.

Unless your implementation of Pascal does not store parameters and local
variables in stack frames for some reason.  Such an implementation might
not support any form of recursion, or only limited recursion.

[...]

> Lawrence D'Oliveiro
> Computer Services Dept, University of Waikato, Hamilton, Nuke-Freeland
> ldo@waikato.ac.nz
> Disk lamer: none of my disks can walk, therefore nothing I say is true.

Scott Bayes
Hewlett-Packard Company
MSO Tech Support