If you know languages like Python or D you know, that nested
functions can be really handy.
Though some compilers (looking at GCC) provide the extension of
nested functions, I wonder, how one could implement an
equivalent behaviour with plain C (in this case I'm thinking of
the language I'm developing, which shall be converted into C for
target compilation). So far I didn't touch the topic "nested
functions", since I just don't see an elegant way to implement
them, but I want them, .
The problem is, that a nested functions resides within the scope
of the enclosing function and thus sees all variables of that.
Of course, if I were not seeking for portability, I could just
fiddle around with assembler on the stack. But I'd like to do as
much in C as possible.
So far the "best" solution I came up with was to create a struct
for each function, containing all it's variables:
struct _foo_variables {
int a;
int b;
short c;
/* ... */
};
static void _nest_foo_bar(struct _foo_variables * const
_foo_variables)
{
}
void foo()
{
struct _foo_variables _variables;
/* ... */
_nest_foo_bar(&_variables);
}
But this doesn't look very elegant.
By nature nested functions can only be called from within the
scope of the enclosing function. I wonder if there's a more
elegant way, to access a calling function's variables from the
called function. I presume not, but maybe I'm wrong. I'm most
concerned about the performance impact due to the need of
dereferencing stuff - most architectures are more efficient in
addressing stuff on the stack, than from arbitrary pointers,
even if they point on the stack. I don't know how good compilers
are nowadays to figure out what's going on, and optimizing this
into frame pointer relative access. Yeah, I know "premature
optimization..."
lambda expressions were implemented quite easyly using the ffcall
library; lambdas (how I specified them for my language) can't
access variables outside the scope anyway, since they're first
class objects to be passed around.
Of course I could just omit the whole idea of nested functions,
but they're so damn usefull in some occasions.
Wolfgang Draxinger
--
E-Mail address works, Jabber: he******@jabber.org, ICQ: 134682867