Skip to content
Tech News
← Back to articles

Implementation of GCC's Nested Functions (vs. C++ Lambdas)

read original more articles
Why This Matters

A GCC maintainer walks through how the compiler actually implements nested functions in C — not via the classic PASCAL-style stack-frame pointer, but by collecting captured variables into a synthetic struct passed to the inner function, which turns out to closely mirror how C++ lambdas capture by reference. The detail matters now because WG14 is weighing proposal N3884 to standardize non-capturing local functions declared static, potentially bringing a long-standing GCC extension into standard C.

Key Takeaways

Implementation of GCC's Nested Functions (vs. C++ Lambdas)

Martin Uecker, 2026-09-05

Introduction

Here, I want to explain how GCC's nested function are implemented. I am not going to discuss taking the address of a nested function that may require the creation of a trampoline. We discussed this topic - and how to get around it - already in several previous blog posts. Instead, I want to describe the basic mechanism that is used to access variables of a parent function.

Nested Functions

Let us start with a very simple example.

int foo(int k) { int bar(int x) { return x + 1; } return bar(k); }

Here, the nested function does not access any variable of the parent function. In this case, it can simply be lifted out of the parent function and be compiled as a separate function. Such functions can still can be useful to define small helper functions, or when locally defining a type that can then be used in the nested function. WG14 is currently considering proposal N3884 that would allow such non-capturing local functions when defined with the static storage class.

But let's consider an example where a nested function accesses a variable of the parent function.

... continue reading