🌐
MathWorks
mathworks.com › matlab › programming › functions › function creation
Nested Functions - MATLAB & Simulink
A nested function is a function that is completely contained within a parent function. Any function in a program file can include a nested function. For example, this function named parent contains a nested function named nestedfx:
🌐
W3Schools
w3schools.com › r › r_functions_nested.asp
R Nested Functions
The function tells x to add y. The first input Nested_function(2,2) is "x" of the main function.
function defined inside another function
In computer programming, a nested function (or nested procedure or subroutine) is a named function that is defined within another (enclosing) block and is lexically scoped within the enclosing block – meaning … Wikipedia
🌐
Wikipedia
en.wikipedia.org › wiki › Nested_function
Nested function - Wikipedia
August 26, 2026 - Programming language support for nested functions varies. With respect to structured programming languages, it is supported in some outdated languages such as ALGOL, Simula 67 and Pascal and in the commonly used JavaScript. It is commonly supported in dynamic and functional languages. However, it is not supported in some commonly used languages including standard C and C++. Other programming technologies provide similar benefit. For example...
🌐
Microsoft Support
support.microsoft.com › en-us › excel › use-nested-functions-in-an-excel-formula
Use nested functions in an Excel formula | Microsoft Support
Using a function as one of the arguments in a formula that uses a function is called nesting. This function is a nested function. For example, by nesting the AVERAGE and SUM functions in the arguments of the IF function, the following formula sums a set of numbers (G2:G5) only if the average ...
🌐
Reddit
reddit.com › r/c_programming › what are some use cases of nested functions?
r/C_Programming on Reddit: What are some use cases of nested functions?
February 8, 2024 -

I know that they're a gcc extension and not standard, but I just wanted to know what makes them useful? Is there any task where using this extension makes things much easier than attempting to stick with the ISO standard?

Top answer
1 of 5
11
The nice thing is that a nested function can access your local variables. So, you can manipulate them without passing pointer arguments. For example, let's say you have a function that is parsing text from a stream, and has several variables to keep track of the input state. You can have a read_next_character() function to get the next character, and it can update all these local variables as appropriate. Without nested functions, you could do this by putting those variables into a struct and passing a pointer to a struct, but might be convenient to avoid that if you're calling your function in 200 different places. Another way to accomplish this is with a macro, but then macros have their own problems. Another situation I can think of where this might be convenient is when you have a function that will be recursive, but you have an initial setup and a bundle of data that gets passed along to every recursive invocation. For example, let's say you have a sort function, and you initially set up a buffer and some boundaries, then you call a recursive function to do the actual sorting; if you make the recursive part a nested function then it can access that state without needing to pass it along as arguments, or as a struct pointer. Again this is really convenience, it doesn't let you do anything you couldn't do otherwise. It's possible that in the past, using nested functions in this way could also get you better performance by avoiding argument passing, without the problems of using global variables. I doubt this is normally true today with the optimization we have, but I imagine it might've been part of the original justification for the feature.
2 of 5
2
there are a few uses but in general it lets you share your local state with the nested function. lets say you have a really complicated long function but you figure out there's some regularity that you can factor out into a function but when you're done this function needs a bunch of parameters and a few pointer out parameters because you need more than one return value because what the nested function does initself is still pretty intricate. the "greybeard" approach to cleaning this up is to make a context struct that contains all this information and you can just move that around and fill it as necessary. the "new c" approach would be to make that secondary function a nested function and let the nested function access any local that it needs from the parent function.
🌐
Coddy.Tech
coddy.tech › learn › courses › function declarations in javascript › nested function
Nested Function – Function Declarations in JavaScript
... Your task is to create a nested function named calculateTaxAmount should takes the price and taxRate from the outer function calculateWithTax and Calculates tax amount and returns it.
🌐
GNU
gnu.org › software › c-intro-and-ref › manual › html_node › Nested-Functions.html
Nested Functions (GNU C Language Manual)
(The ability to do this is indispensable for automatic translation of certain programming languages into C.) The nested function’s name is local to the block where it is defined. For example, here we define a nested function named square, then call it twice:
Find elsewhere
🌐
Microsoft MakeCode
arcade.makecode.com › courses › csintro4 › appendix › nested-functions
Advanced Topics: Nested Functions
The creation of a nested function is fairly simple: just declare the function as it is normally done, only within the scope of another function.
🌐
Wolfram MathWorld
mathworld.wolfram.com › NestedFunction.html
Nested Function -- from Wolfram MathWorld
April 15, 2004 - Function nesting is implemented in the Wolfram Language as Nest[f, expr, n], and a listing of incremental nestings is implemented as NestList[f, expr, n]. Integrals of nested functions rapidly become difficult to find in exact form. For example, the first two nestings of the exponential function ...
🌐
Colinsblog
colinsblog.net › 2023-08-05-nesting-functions
Better Code Organization by Nesting Functions - Colin's Notes
August 5, 2023 - If you use a standard fn declaration inside another function you can’t access the enclosing scope at all. In some cases that’s fine for pure organization improvements. That way there’s no confusion about when the state of local variables gets read or written. When using closures the borrow checker makes sure any variables used inside the closure from the enclosing scope are owned by the closure making writing to them outside the closure illegal. program nested_demo; function outer(x: integer): integer; var n: integer = 99; m: integer = 99; function inner(y: integer): integer; begin inner := y * 10 * m + n end; begin m:= 2; n := 1; outer := inner(x) end; begin writeln(outer(9)) end.
🌐
CodeHS
codehs.com › glossary › term › 16
Glossary Term: Nested Function | CodeHS
**This should be avoided.** An example of a nested function: function start() { move(); function turnRight() { turnLeft(); turnLeft(); turnLeft(); } turnRight(); move(); ... } Instead, your functions should be defined *after* the other functions ...
Top answer
1 of 8
10

Your question made me curious, so I looked in some real-world code: the Python standard library. I found 67 examples of nested functions. Here are a few, with explanations.

One very simple reason to use a nested function is simply that the function you're defining doesn't need to be global, because only the enclosing function uses it. A typical example from Python's quopri.py standard library module:

def encode(input, output, quotetabs, header = 0):
    ...
    def write(s, output=output, lineEnd='\n'):
        # RFC 1521 requires that the line ending in a space or tab must have
        # that trailing character encoded.
        if s and s[-1:] in ' \t':
            output.write(s[:-1] + quote(s[-1]) + lineEnd)
        elif s == '.':
            output.write(quote(s) + lineEnd)
        else:
            output.write(s + lineEnd)

    ...  # 35 more lines of code that call write in several places

Here there was some common code within the encode function, so the author simply factored it out into a write function.


Another common use for nested functions is re.sub. Here's some code from the json/encode.py standard library module:

def encode_basestring(s):
    """Return a JSON representation of a Python string

    """
    def replace(match):
        return ESCAPE_DCT[match.group(0)]
    return '"' + ESCAPE.sub(replace, s) + '"'

Here ESCAPE is a regular expression, and ESCAPE.sub(replace, s) finds all matches of ESCAPE in s and replaces each one with replace(match).


In fact, any API, like re.sub, that accepts a function as a parameter can lead to situations where nested functions are convenient. For example, in turtle.py there's some silly demo code that does this:

    def baba(xdummy, ydummy):
        clearscreen()
        bye()

    ...
    tri.write("  Click me!", font = ("Courier", 12, "bold") )
    tri.onclick(baba, 1)

onclick expects you to pass an event-handler function, so we define one and pass it in.

2 of 8
9

Decorators are a very popular use for nested functions. Here's an example of a decorator that prints a statement before and after any call to the decorated function.

def entry_exit(f):
    def new_f(*args, **kwargs):
        print "Entering", f.__name__
        f(*args, **kwargs)
        print "Exited", f.__name__
    return new_f

@entry_exit
def func1():
    print "inside func1()"

@entry_exit
def func2():
    print "inside func2()"

func1()
func2()
print func1.__name__
🌐
w3reference
w3reference.com › blog › real-world-examples-of-nested-functions
Real-World Nested Functions: Practical Examples to Understand Their Use Cases — w3reference.com
Use Case: When a small utility function is only needed by one parent function, nesting it avoids cluttering the global namespace. Example: User Registration with Email Validation Suppose you’re building a user registration system. The core logic (e.g., storing the user) needs email validation, but the validation function is irrelevant elsewhere.
🌐
CustomGuide
customguide.com › excel › nested-function-excel
Nested If Function in Excel | CustomGuide
The syntax for nested functions will vary greatly, as the combinations for combining functions is nearly limitless. Here’s an example of what a nested function might look like: =IF(D2>AVERAGE($B$2:$B$10),"Yes","No").
🌐
Dive into Python
diveintopython.org › home › learn python programming › functions in python › nested functions
Nested Functions in Python - Powerful Tool for Organized Code
May 3, 2024 - In this example, square is a nested function. It is defined inside exponential. exponential takes in a parameter x. exponential returns the square of x raised to the fourth power. square takes in a parameter y. It returns the square of y.
🌐
GNU
gcc.gnu.org › onlinedocs › gcc › Nested-Functions.html
Nested Functions (Using the GNU Compiler Collection (GCC))
The nested function’s name is local to the block where it is defined. For example, here we define a nested function named square, and call it twice:
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-nested-functions
JavaScript Nested functions - GeeksforGeeks
The outer() function is defined with two parameters a and b. Inside outer(), there is a nested function inner() that returns the sum of a and b.
Published: July 12, 2025
🌐
Analytics Vidhya
analyticsvidhya.com › home › how nested functions are used in python?
How nested functions are used in Python? - Analytics Vidhya
March 4, 2025 - For example, in Python: def outer_function(x): def inner_function(y): return x + y return inner_function Here, inner_function is nested inside outer_function and can access variables from its enclosing scope, like x.
🌐
ScienceDirect
sciencedirect.com › topics › computer-science › nested-function
Nested Function - an overview | ScienceDirect Topics
For example, the following function calculates and returns the volume of a cube. Three arguments are passed to it, for the length and width of the base of the cube, and also the height. The outer function calls a nested function that calculates and returns the area of the base of the cube.