Tom St Denis <to*@securescience.net> writes:
Alexander Bartolich wrote:
begin followup to Malcolm: No. You can get most of the functionality of local functions by
placing your function in a file of its own, and then declaring
the sub-functions as static functions in the same file.
No, that's not what nested functions are about.
They have access to the local variables of their parent functions.
so you make
int test(void)
{
int a, b;
int test2(void) { return a + b; }
a = 4; b = 5;
return test2() + 3;
}
can be turned into
---
static int a, b;
static int test2(void) { return a + b; }
int test(void) { a = 4; b = 5; return test2() + 3; }
---
That's not the same thing at all. In the nested-function version
(which is not valid C), a and b are local variables, so each
invocation of test() gets its own unique copy of each of them. In
your static version, the lifetime of a and b is the entire execution
of the program; recursive calls to test() will share the same copies.
If your goal is to create a function that does the same thing as the
original one, you might as well write
int test(void)
{
return 12;
}
If you want to write something that duplicates the semantics of nested
functions with access to the parent's local variables, it's possible
(though probably not worth the effort), but making the local variables
static isn't the way to do it.
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"