A nested function is a function encapsulated within another function. It can only be called by the enclosing function or by functions directly or indirectly nested within the same enclosing function. In other words, the scope of the nested function is limited by the enclosing function. An example in C-syntax:
int E(int x) { int F(int y) { return x + y; } return F(3); }
In this case the function F is nested within E (note that x is visible in F, while y is invisible outside F).
Nested functions are a form of information hiding and are useful for dividing procedural tasks into subtasks which are only meaningful locally; it avoids cluttering other parts of the program with functions, variables, etc. unrelated to those parts.
Well known languages supporting nested functions include
In Scheme and most other functional programming languages, nested functions are a common way of implementing algorithms with loops in them. A simple (tail) recursive inner function is created, which behaves as the algorithm's main loop, while the outer function performs startup actions that only need to be done once. In more complex cases, a number of mutually recursive functions may be created as inner functions.
This article is licensed under the GNU Free Documentation License.
It uses material from the
"Nested function".
Home Page • arts • business • computers • games • health • hospitals • home • kids & teens • news • physicians • recreation• reference • regional • science • shopping • society • sports • world