Re: Local Functions...
In message <8NbBi.7234$ZA.3905@newsb.telia.net>, Erik Wikstr?m
<Erik-wikstrom@telia.com> writes
On 2007-08-29 11:33, deepakvsoni@gmail.com wrote:
Why does C++ restrict definition of functions with in functions?
int f1() {
int f2() {
.....
}
} //This is not supported.
Thanks in advance to anybody who replies..
I have not studied the idea in detail but I can't come up with anything that
can be accomplished with nested functions that can't be done with
normal functions.
Nested functions would, in principle, have access to the local variables
of their containing function:
int f1() {
int i;
int f2() {
int j = i;
/* do stuff */
}
i = 1;
f2();
i = 2;
f2();
}
Making this work in practice, where the inner function might be invoked
recursively or indirectly, involves an extra level of indirection, which
means more work for the compiler and a potential performance hit at
runtime. Some languages (e.g. Pascal and some of the Algol family IIRC)
allow this; C and C++ follow their parent BCPL by simply banning such
things (actually BCPL allowed nested function definitions but outlawed
access to the parent function's local variables, so all the nested
declaration achieved was to reduce the scope of the inner function.)
In fact I find it a bit limiting since f2() can't be called from a scope outside
f1(),
In the example above, what would f2() use for "i" ?
which means that you can't reuse f2() in some other context.
That's called "encapsulation" and is normally regarded as a Good Thing
;-)
--
Richard Herring