Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 135 ยท Functions

Nested Functions (GNU Extension) and Alternatives

Standard C has no nested functions. See how the GCC extension works, why it is risky, and the portable alternatives, from static helpers to callbacks with a context.

In Python, JavaScript or Pascal you can define a function inside another function, and the inner one can read the outer one's local variables. People coming from those languages often try the same in C and get a compile error. Standard C has no nested functions: every function is defined at file scope, and function definitions cannot appear inside a block.

That does not mean the idea is useless in C. GCC offers it as an extension, and standard C has dependable ways to get the same result. This lesson shows what the extension does, what it costs, and the portable pattern most real C code uses instead: a callback plus a context pointer. You should already know Function Pointers and void Pointers.

What standard C allows

This code is rejected by every strict C compiler, and by Clang:

C
int main(void)
{
    int helper(int x) { return x * 2; }   /* error: function definition inside a function */
    return helper(21);
}

What you can do inside a function is declare another function (a prototype) with block scope, or define a static helper at file scope above it. The latter is the usual standard solution when you only want to keep a helper private to a file.

The GCC extension

GCC (the compiler behind the sandbox) accepts nested function definitions as a documented extension, as long as you don't ask for strict ISO mode with -pedantic-errors. The inner function can use the local variables of the enclosing function that are in scope where it is defined:

C A GCC nested function reading its parent's variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The second call prints 105: the nested function does not copy offset, it reaches into the enclosing function's stack frame. That is convenient, but it explains the extension's limits. A nested function only works while its parent is still running. If you return a pointer to it, or store the pointer somewhere that outlives the parent, calling it later uses a stack frame that no longer exists, which is undefined behavior.

Passing a nested function as a callback

The most common use is giving a nested function to something that expects a function pointer, such as a sorting comparator, so the comparator can use local data:

C A nested comparator for qsort

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

qsort has no way to hand extra data to its comparator, so the nested function is doing something plain C cannot do directly. Behind the scenes GCC builds a small piece of machine code called a trampoline on the stack, so the nested function's address can be called like a normal function pointer and still find the parent's variables.

That trampoline is the price: when you run the example above, the linker prints a warning that the program requires executable stack. On most systems it requires an executable stack, which weakens security (injected code could run there), so some distributions, linkers and static analyzers warn about or forbid it. The code is also GCC-specific: Clang does not support the extension, and the same file will not compile on MSVC or macOS's default compiler. For portable programs and libraries, avoid it. The sandbox's compiler happens to work with it, but treat it as a curiosity.

Do not use nested functions in code that must build with Clang, MSVC, or in environments with a non-executable stack policy. If you take the address of a nested function, the stack may need to be executable; a nested function that you only call directly does not need a trampoline.

Portable alternative 1: static helper functions

If the inner function does not need the outer function's local variables, simply define it at file scope as static. It stays private to the file and is as fast as a nested function:

C
static int double_it(int x)
{
    return x * 2;
}

Most nested functions people write are really just helpers like this. Grouping related helpers together and putting them above their user keeps the code readable.

Portable alternative 2: pass the data explicitly

When the helper does need data, pass that data as a parameter, preferably in a struct. The plain-C pattern for callbacks follows from this: the callback receives a void * context argument that the caller fills with whatever the callback needs. Many C APIs are built this way (pthread_create, signal handlers with sigaction's siginfo, GUI toolkits). The standard qsort lacks the extra argument. glibc offers a non-standard qsort_r that has one (and C11's optional Annex K has qsort_s), but their argument orders differ between systems. Writing your own sorting or iteration function with a context parameter avoids the question.

C The context-struct pattern, fully portable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The comparator is an ordinary file-scope function. Everything it needs travels in struct sort_options, reached through the void *context parameter, and the type is checked by one cast at the top. The same code compiles with every C compiler, works whether or not the stack is executable, and the function pointer remains valid for the whole program. As a bonus, you can store the pair (function, context) in a struct and call it much later, which nested functions cannot do safely.

Which approach to choose

Need Use
A private helper without access to locals static function at file scope
A callback that needs some data Callback plus void *context struct
Quick experiment in GCC-only code GNU nested function (call directly)
Anything that must outlive the caller Context struct allocated by the caller, never a nested function

C23 does not add lambdas or closures, so the context-struct pattern remains the standard answer.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which statement about nested functions in standard C is true?

    ISO C requires every function to be defined at file scope. Nested functions are a GCC extension.
  2. 2. What is the danger of storing a pointer to a GCC nested function and calling it after the parent returned?

    A nested function accesses its parent's stack frame. After the parent returns that frame is gone.
  3. 3. Why does taking the address of a nested function often need an executable stack?

    The trampoline lets the address be called like an ordinary function pointer while still reaching the parent's variables, but it lives on the stack.
  4. 4. What is the portable way to give a callback access to extra data?

    A context pointer carries the data explicitly, works in every compiler and stays valid as long as the struct does.

Summary

  • Standard C has no nested functions; function definitions go at file scope. Use static to keep a helper private to a file.
  • GCC accepts nested functions as an extension: they can read the enclosing function's locals but only while the parent is still running.
  • Passing a nested function's address needs a stack trampoline (and often an executable stack); the code is not portable to Clang or MSVC.
  • The portable replacement is a plain function that receives a void *context argument pointing to a struct with the data it needs.
  • C23 still has no closures or lambdas, so the context pattern remains the standard approach.

Next: Arrays starts the next chapter, where you'll store many values under one name.