# Nested function

> Mediated Wiki article. Canonical URL: https://mediated.wiki/source/Nested_function
> Markdown URL: https://mediated.wiki/source/Nested_function.md
> Source: https://en.wikipedia.org/wiki/Nested_function
> Source revision: 1353876857
> License: Creative Commons Attribution-ShareAlike 4.0 International (https://creativecommons.org/licenses/by-sa/4.0/)

Named function defined within a function

In [computer programming](/source/Computer_programming), a **nested function** (or **nested procedure** or **subroutine**) is a [named](/source/Identifier) [function](/source/Subroutine) that is defined within another (enclosing) block and is [lexically scoped](/source/Lexically_scoped) within the enclosing block – meaning it is only callable by name within the body of the enclosing block and can use [identifiers](/source/Identifiers) declared in outer [blocks](/source/Block_(programming)), including outer functions. The enclosing block is typically, but not always, another function.

[Programming language](/source/Programming_language) support for nested functions varies. With respect to [structured programming](/source/Structured_programming) languages, it is supported in some outdated languages such as [ALGOL](/source/ALGOL), [Simula 67](/source/Simula_67) and [Pascal](/source/Pascal_(programming_language)) and in the commonly used [JavaScript](/source/JavaScript). It is commonly supported in [dynamic](/source/Dynamic_language) and [functional](/source/Functional_language) languages. However, it is not supported in some commonly used languages including standard [C](/source/C_language) and [C++](/source/C%2B%2B).

Other programming technologies provide similar benefit. For example, a [lambda function](/source/Lambda_function_(computer_programming)) also allows for a function to be defined inside of a function (as well as elsewhere) and allows for similar data hiding and encapsulation. Notably, a lambda function has no name (is anonymous) and therefore cannot be called by name and has no visibility aspect.

## Attributes

The [scope](/source/Scope_(computer_science)) of a nested function is the block that contains it – be it a function block or block within a function body. It is not visible (cannot be called by name) outside its containing block.

A nested function can use [identifiers](/source/Identifiers) (i.e. the name of functions, variables, types, classes) declared in any enclosing block, except when they are masked by inner declarations with the same names.

A nested function can be declared within a nested function, recursively, to form a deeply nested structure. A deeply nested function can access identifiers declared in all of its enclosing blocks, including enclosing functions.

Nested functions may in certain situations lead to the creation of a [closure](/source/Closure_(computer_programming)). If it is possible for the nested function to [escape](/source/Escape_analysis) the enclosing function, for example if functions are [first class objects](/source/First_class_object) and a nested function is passed to another function or returned from the enclosing function, then a closure is created and calls to this function can access the environment of the original function. The frame of the immediately enclosing function must continue to be alive until the last referencing closure dies and [non-local](/source/Non-local_variable) [automatic variables](/source/Automatic_variable) referenced in closures can therefore not be [stack allocated](/source/Stack_allocation) in languages that allow the closure to persist beyond the lifetime of the enclosing block. This is known as the [funarg problem](/source/Funarg_problem) and is a key reason why nested functions was not implemented in some simpler languages as it significantly complicates code generation and analysis, especially when functions are nested to various levels, sharing different parts of their environment.

## Value

The nested function technology allows a [programmer](/source/Programmer) to write [source code](/source/Source_code) that includes beneficial attributes such as [information hiding](/source/Information_hiding), [encapsulation](/source/Encapsulation_(computer_programming)) and [decomposition](/source/Decomposition_(computer_science)). The programmer can divide a task into subtasks which are only meaningful within the context of the task such that the subtask functions are hidden from callers that are not designed to use them.

Block scoping allows functions to share the state of enclosing blocks (including enclosing functions) without passing [parameters](/source/Parameter_(computer_programming)) or using [global variables](/source/Global_variable).[1]

## Uses

### Helper

A nested function typically acts as a [helper function](/source/Wrapper_function) or a [recursive function](/source/Recursion_(computer_science)).

### Control flow

Nested functions can be used for unstructured [control flow](/source/Control_flow), by using the return statement for general unstructured control flow. This can be used for finer-grained control than is possible with other built-in features of the language – for example, it can allow early termination of a for loop if break is not available, or early termination of a nested [for loop](/source/For_loop) if a multi-level break or exceptions are not available.

### Higher-order functions

Main article: [Higher-order function](/source/Higher-order_function)

In some languages, it is possible to create a nested function that accesses a set of parameters from the outer function, that is a [closure](/source/Closure_(computer_programming)), and have that function be the outer function's return value. Thus it is possible to return a function that is set to fulfill a certain task with little or no further parameters given to it, which can increase performance quite significantly.[2]

## Examples

### Simple example

A simple example in Pascal:

function E(x: real): real;
    function F(y: real): real;
    begin
        F := x + y
    end;
begin
    E := F(3) + F(4)
end;

The function F is nested within E. Note that E's parameter x is also visible in F (as F is a part of E) while both x and y are invisible outside E and F respectively.

Similarly, in [Standard ML](/source/Standard_ML):

fun e (x : real) =
  let
    fun f y = x+y
  in
    f 3 + f 4
  end;

In [Haskell](/source/Haskell_(programming_language)):

e :: Float -> Float
e x = f 3 + f 4 where f y = x + y

In [PL/I](/source/PL%2FI):

e: procedure(x) returns(float);
  declare x float;
  f: procedure(y) returns(float);
    declare y float;
    return x + y
    end;
  return f(3.0) + f(4.0);
  end;

In [Python](/source/Python_(programming_language)):

def e(x: float) -> float:
    def f(y: float) -> float:
        return x + y
    return f(3.0) + f(4.0)

In [GNU C](/source/GNU_Compiler_Collection)[3] – which extends standard C with nested functions:

float e(float x) {
    float f(float y) {
        return x + y;
    }
    return f(3.0f) + f(4.0f);
}

### Quicksort

The following is an implementation of [quicksort](/source/Quicksort):[4]

void sort(int* items, int size) {
    void quickSort(int first, int last) {
        void swap(int p, int q) {
            int tmp = items[p];
            items[p] = items[q];
            items[q] = tmp;
        }

        int partition() {
            int pivot = items[first];
            int index = first;
            swap(index, last);
            for (int i = first; i < last; i++) {
                if (items[i] < pivot) {
                    swap(index++, i);
                }
            }
            swap(index, last);
            return index;
        }

        if (first < last) {
            int pivotIndex = partition();
            quickSort(first, pivotIndex - 1);
            quickSort(pivotIndex + 1, last);
        }
    }
    quickSort(0, size - 1);
}

The following is an implementation of the [Hoare partition based quicksort](/source/Quicksort#Hoare_partition_scheme) using [C++11](/source/C%2B%2B11#Lambda_functions_and_expressions) [lambda expression syntax](/source/Anonymous_function#C.2B.2B_.28since_C.2B.2B11.29) which is an alternative technology that also allows hiding a function inside a function:

// Iter represents a random access iterator
template <typename Iter>
void sort(Iter begin, Iter end) {
	auto partition = [&]() -> Iter {
		// Hoare partition scheme
		Iter& pivot = *begin;
		Iter forwardCursor = begin;
		Iter backwardCursor = end - 1;
		Iter partitionPositionFound = false;

		auto locatePartitionPosition = [&]() -> void {
			while (*forwardCursor < pivot) {
				++forwardCursor;
            }
			while (pivot < *backwardCursor) {
				--backwardCursor;
            }
			if (forwardCursor >= backwardCursor) {
				partitionPositionFound = true;
			} else
				swap(*forwardCursor, *backwardCursor);
            }
		};

		// Trivial helper function
		auto moveOnAndTryAgain = [&]() -> void {
			++forwardCursor;
			--backwardCursor;
		};

		// Brief outline of the actual partition process
		while (true) {
			locatePartitionPosition();
			if (partitionPositionFound)
				return backwardCursor + 1;
			else {
				moveOnAndTryAgain();
            }
		}
	};

	// Brief outline of the quicksort algorithm
	if (begin < end - 1) {
		Iter partitionPosition = partition();
		sort(begin, partitionPosition);
		sort(partitionPosition, end);
	}
}

## Languages

Notable languages supporting nested functions include:

- [ALGOL](/source/ALGOL)-based languages such as [ALGOL 68](/source/ALGOL_68), [Simula](/source/Simula), [Pascal](/source/Pascal_(programming_language)), [Modula-2](/source/Modula-2), [Modula-3](/source/Modula-3), [Oberon](/source/Oberon_(programming_language)), [PL/I](/source/PL%2FI), and [Ada](/source/Ada_(programming_language))

- Modern versions of [Lisp](/source/Lisp_(programming_language)) (with lexical scope) such as [Scheme](/source/Scheme_(programming_language)), and [Common Lisp](/source/Common_Lisp)

- [ECMAScript](/source/ECMAScript) ([JavaScript](/source/JavaScript) and [ActionScript](/source/ActionScript))

- [Dart](/source/Dart_(programming_language))[5]

- [Kotlin](/source/Kotlin_(programming_language)) (local functions[6])

- [Rust](/source/Rust_(programming_language))

- [Scala](/source/Scala_(programming_language)) (nested functions[7])

- Various degrees of support in scripting languages such as [Ruby](/source/Ruby_(programming_language)), [Python](/source/Python_(programming_language)), [Lua](/source/Lua_(programming_language)), [PHP](/source/PHP) and [Perl](/source/Perl)

- [GCC](/source/GNU_Compiler_Collection) supports nested functions in C, as a language extension.[8]

- [C#](/source/C_Sharp_(programming_language)), starting with C# 7.0

- The [D](/source/D_(programming_language)) language, a C-related language with nested functions.

- [Fortran](/source/Fortran), starting with [Fortran-90](/source/Fortran#Fortran_90), supports *a single level* of nested (*CONTAINed*) subroutines and functions.

- [MATLAB](/source/MATLAB) (full support)

- [Wolfram Language](/source/Wolfram_Language)

- [Golang](/source/Go_(programming_language)) (Function closures[9])

### Functional languages

In most [functional programming](/source/Functional_programming) languages, such as Scheme, nested functions are a [common way](/source/Programming_idiom) of implementing [algorithms](/source/Algorithm) with loops in them. A simple ([tail](/source/Tail_recursion)) [recursive](/source/Recursion) 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.

## Alternatives

Various alternative techniques can be used to achieve similar programming results as via nested functions.

### Modularity

A common alternative is to leverage a language's modularity technology. Some functions are exposed for use outside of the module and some are only visible within the module.

In C, this can be implemented by declaring functions and variables as *static* to hide them from code outside the file.[10] This allows for data hiding, encapsulation and decomposition, but at a different level of [granularity](/source/Granularity) than with nested functions. This modularity does not support more than one level of nesting.

In [object-oriented languages](/source/Object-oriented_languages), a class typically provides a scope in which functions and state can be hidden from consumers of the class but accessible within the class. Some languages allow classes to be nested.

### Parameters

To implement data hiding, functions can pass around shared data as parameters, but this increases the complexity of function calls.[1]

In C, this is generally implemented by passing a pointer to a structure containing the shared data.[10]

### Lambda

In [PHP](/source/PHP) and other languages, the [lambda](/source/Anonymous_function) is an alternative. A function is defined in a code statement rather than declared with the usual function syntax. It has no name but is callable via a [function reference](/source/Function_reference). Such functions can be defined inside of a function as well as in other scopes. To use local variables in the anonymous function, use [closure](/source/Closure_(computer_science)).

### Alternatives by language

The following languages provide features that are similar to nested functions:

- [C++](/source/C%2B%2B) – classes allow for similar data hiding and encapsulation; defining a class within a class provides similar structure (see [Function object in C++](/source/Function_object#In_C_and_C.2B.2B))

- [C++11](/source/C%2B%2B11) and later – via lambda expressions (see quicksort example above)[11]

- [Eiffel](/source/Eiffel_(programming_language)) – explicitly disallows nesting of routines to keep the language simple; does allow the convention of using a special variable, **Result**, to denote the result of a (value-returning) function

- [C#](/source/C_Sharp_(programming_language)) and [Visual Basic](/source/Visual_Basic_.NET) – via lambda expressions

- [Java](/source/Java_(programming_language)) – since Java 8, via [lambda expressions](/source/Anonymous_function#Java)[12], and in older versions, via an [anonymous class](/source/Anonymous_class) containing a single method

## Implementation

See also: [Man or boy test](/source/Man_or_boy_test)

Implementation of nested functions can be more involved than it may appear, as a reference to a nested function that references non-local variables creates a [closure](/source/Closure_(computer_science)). For this reason nested functions are not supported in some languages such as C, C++ or Java as this makes compilers more difficult to implement.[10][13] However, some compilers do support them, as a compiler specific extension. A well known example of this is the [GNU C](/source/GNU_C) implementation of C which shares code with compilers for languages such as Pascal, Ada and Modula.

### Access of non-local objects

There are several ways to implement nested procedures in a lexically scoped language, but the classic way is as follows:

- Any [non-local object](/source/Non-local_object), X, is reached via access-links in the [activation frames](/source/Call_stack) on the machine stack. The caller, C, assists the called procedure, P, by pushing a *direct* link to the *latest* activation of P's immediate lexical encapsulation, (P), prior to the call itself. P may then quickly find the right activation for a certain X by following a *fixed number* (P.depth – X.depth) of links (normally a small number).

- The caller creates this direct link by (itself) following C.depth – P.depth + 1 older links, leading up to the latest activation of (P), and then *temporarily* bridging over these with a direct link to that activation; the link later disappears together with P, whereby the older links beneath it may come into use again.

- Note that P is visible for, and may therefore be called by, C if (P) = C / (C) / ((C)) / etc.

This original method is faster than it may seem, but it is nevertheless often optimized in practical modern compilers (using [*displays*](/source/Call_stack#Display) or similar techniques).

Another way to implement nested functions that is used by some compilers is to convert ("lift") nested functions into non-nested functions (where extra, hidden, parameters replace the access links) using a process known as [lambda lifting](/source/Lambda_lifting) during an intermediate stage in the compilation.

### Functions as values

In order for local functions with [lexically scoped](/source/Lexically_scoped) [nonlocals](/source/Non-local_variable) to be passed as results, the language runtime code must also implicitly pass the environment (data) that the function sees inside its encapsulating function, so that it is reachable also when the current activation of the enclosing function no longer exists.[14] This means that the environment must be stored in another memory area than (the subsequently reclaimed parts of) a chronologically based execution stack, which, in turn, implies some sort of freely [dynamic memory allocation](/source/Dynamic_memory_allocation). Many older Algol based languages (or dialects thereof) does therefore not allow local functions that access nonlocals to be passed as return values, or do they not allow functions as return values at all, although passing of such functions as arguments may still be possible.

### No-execute stacks

[GCC](/source/GNU_Compiler_Collection)'s implementation of nested functions in C causes a loss of [no-execute](/source/NX_bit) [stacks](/source/Call_stack) (NX stacks). Therefore, software engineered using [Secure Development Lifecycle](/source/Software_Development_Security) often do not allow the use of GCC's nested functions.[15] By default, GCC will issue a brief notification when a generated object file requires an executable stack. For a clear warning when compiling C code, use the ‑Wtrampolines option.

The problem occurs because GCC uses "trampolines" (executable code on the stack) to jump to nested functions .[16] The GCC project has an alternative method that could provide nested functions via non-executable descriptors, however it is currently only used in GCC's [Ada](/source/Ada_(programming_language)) compiler.

## See also

- [Call stack](/source/Call_stack)

- [Closure (computer science)](/source/Closure_(computer_science))

- [Function composition (computer science)](/source/Function_composition_(computer_science))

- [Inner class](/source/Inner_class)

- [Nesting (computing)](/source/Nesting_(computing))

## References

1. ^ [***a***](#cite_ref-FOOTNOTEBright2004_1-0) [***b***](#cite_ref-FOOTNOTEBright2004_1-1) [Bright 2004](#CITEREFBright2004).

1. **[^](#cite_ref-Higher-Order_Functions_and_Lambdas_–_Kotlin_Programming_Language_2-0)** [Higher-Order Functions and Lambdas - Kotlin Programming Language](http://kotlinlang.org/docs/reference/inline-functions.html)

1. **[^](#cite_ref-3)** Rothwell, Trevis J. (2011). *The GNU C Reference Manual*. Free Software Foundation, Inc. p. 63.

1. **[^](#cite_ref-4)** [Re: Nesting functions- Why?](https://archive.today/20130703055646/http://www.dreamincode.net/forums/topic/262883-nesting-functions-why/page__p__1530693&%23entry1530693), [baavgai](https://web.archive.org/web/20100405113726/http://www.dreamincode.net/forums/user/52176-baavgai/), 14 January 2012

1. **[^](#cite_ref-5)** ["A tour of the Dart language"](https://dart.dev/guides/language/language-tour#lexical-scope).

1. **[^](#cite_ref-6)** ["Functions | Kotlin"](https://kotlinlang.org/docs/functions.html#local-functions).

1. **[^](#cite_ref-7)** ["Nested Methods"](https://docs.scala-lang.org/tour/nested-functions.html).

1. **[^](#cite_ref-8)** ["Nested Functions – Using the GNU Compiler Collection (GCC)"](https://gcc.gnu.org/onlinedocs/gcc/Nested-Functions.html). GNU Project. Retrieved 2007-01-06.

1. **[^](#cite_ref-9)** ["A tour of Go"](https://go.dev/tour/moretypes/25).

1. ^ [***a***](#cite_ref-cfaq_10-0) [***b***](#cite_ref-cfaq_10-1) [***c***](#cite_ref-cfaq_10-2) "[Question 20.24: Why doesn't C have nested functions?](http://c-faq.com/misc/nestfcns.html), comp.lang.c FAQ

1. **[^](#cite_ref-11)** ["Nested function - Rosetta Code"](http://www.rosettacode.org/wiki/Nested_function#C.2B.2B).

1. **[^](#cite_ref-12)** ["Nested function - Rosetta Code"](http://www.rosettacode.org/wiki/Nested_function#Java).

1. **[^](#cite_ref-13)** [answer](https://stackoverflow.com/a/1348456/2025416) by Dave Vandervies, Aug 28 '09 at 17:45, to "[Why are nested functions not supported by the C standard?](https://stackoverflow.com/questions/1348095/why-are-nested-functions-not-supported-by-the-c-standard)"

1. **[^](#cite_ref-14)** Such a combination of function code and its environment is sometimes called a [closure](/source/Closure_(computer_programming)).

1. **[^](#cite_ref-15)** Walton, Jeffrey. ["C-Based Toolchain Hardening"](http://www.owasp.org/index.php/C-Based_Toolchain_Hardening#GCC.2FBinutils). The Open Web Application Security Project (OWASP). Retrieved 28 February 2017.

1. **[^](#cite_ref-16)** ["Trampolines"](https://gcc.gnu.org/onlinedocs/gccint/Trampolines.html). *GCC Internals Documentation*. GNU. Retrieved 12 May 2026.

- Bright, Walter (1 May 2004). ["Nested Functions"](http://www.drdobbs.com/nested-functions/184401792). *[Dr. Dobb's](/source/Dr._Dobb's)*.

## External links

- [comp.lang.c FAQ: Nested Functions](http://c-faq.com/misc/nestfcns.html)

- ["6.4 Nested procedure and functions"](http://www.freepascal.org/docs-html/prog/progse23.html). FreePascal documentation.

---
Adapted from the Wikipedia article [Nested function](https://en.wikipedia.org/wiki/Nested_function) by Wikipedia contributors ([contributor history](https://en.wikipedia.org/wiki/Nested_function?action=history)). Available under [Creative Commons Attribution-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-sa/4.0/). Changes may have been made.
