Nesting of functions

Home / C Programming / Nesting of functions

Nesting of functions


In C programming, nesting of functions refers to the concept of defining a function inside another function. This is also known as "nested functions" or "inner functions." In C, function nesting is not a standard feature, and it is not directly supported by the C language itself.
However, C does allow you to simulate a form of function nesting using a concept called "local functions" or "nested functions." This involves defining functions within the scope of another function, making them accessible only within that function's scope. The nested functions can access variables from the enclosing function, which can be helpful in certain situations.
Please note that local functions or nested functions are not standard C, and they are considered a non-standard extension that may not be supported by all C compilers. If you want to write portable C code, it's best to avoid using nested functions.
Here's an example of how you can simulate nested functions using GCC (GNU Compiler Collection) as it supports nested functions as an extension:



In this example, we have an outer function `outer_function()`, which contains a nested function `inner_function()`. The inner function can access the local variable `x` declared in the outer function.
If you try to compile this code using GCC (with the `-std=gnu99` flag), it should work and produce the following output:
This is the inner function.
Accessing x from the outer function: 10