Example 1 - To Demonstrate Nested Function in C
C
#include <stdio.h>
void outerFunction() {
int x = 10;
void innerFunction() {
printf("Inner function: %d\n", x);
}
innerFunction();
}
int main() {
outerFunction();
return 0;
}
You can also try this code with Online C Compiler
Run Code
Output
Inner function: 10
Explanation
In this example, outerFunction() is defined with a nested function innerFunction() inside it. x is a local variable of outerFunction(). innerFunction() is called within outerFunction(). Inside innerFunction(), it prints the value of x.
Example 2 - Using GCC Extension for Nested Functions in C
C
#include <stdio.h>
int main() {
int x = 10;
void innerFunction() {
printf("Inner function: %d\n", x);
}
innerFunction();
return 0;
}
You can also try this code with Online C Compiler
Run Code
Output
Inner function: 10
Explanation
In this example, the main function contains a nested function innerFunction(). x is a local variable of the main function. innerFunction() is called within the main function. Inside innerFunction(), it prints the value of x.
You can also read about the jump statement and Short int in C Programming
Must Read Passing Arrays to Function in C
Frequently Asked Questions
What is a nested function in C?
In the C programming language, nesting occurs when one or more functions are used within another function. In the C programming language, we cannot define a function within another function (nested function is not supported by C language).
What is nested function also known as?
The nested function is also known as the inner function. Nested functions are nothing but a function defined inside another function. It can be defined in any place that enables the declaration of variables, allowing nested functions inside of nested functions.
What is sub function in C?
A sub function in C refers to a function defined within another function, providing encapsulation and local scope.
What is a nested function formula?
A nested function formula involves defining a function within another function's scope, allowing access to the enclosing function's variables.
Why do we need nested functions?
In order to immediately access the variables and names defined in the enclosing function, we build nested (or inner, nested) functions inside of other functions. Other locally defined functions, variables, constants, types, classes, etc., inside the same scope are accessible.
Conclusion
In this article, we had a look at how we can write nested functions and how they work in C. We hope that this blog has helped you enhance your knowledge regarding Nested Functions and if you would like to learn more, check out Lexical Scoping and Lexical Analysis in Compiler Design and articles on Coding Ninjas Studio. Do upvote our blog to help other ninjas grow. Happy Coding!