In some applications, we find that some functions are declared inside another function. This is sometimes called a nested function, but it's not actually a nested function. This is called lexical scoping. In C, lexical scoping has no effect because the compiler cannot find the correct memory location of the inner function.
Nested function definitions cannot access local variables of surrounding blocks. They can only access global variables. In C, there are two nested scopes: local and global. Therefore, nested functions have some limited uses. If we want to create a nested function like below, an error will be generated.
#include <stdio.h> main(void) { printf("Main Function"); int my_fun() { printf("my_fun function"); // defining another function inside the first function. int my_fun2() { printf("my_fun2 is inner function"); } } my_fun2(); }
text.c:(.text+0x1a): undefined reference to `my_fun2'
But an extension to the GNU C compiler allows nested functions to be declared. To do this, we have to add the auto keyword before the declaration of the nested function.
#include <stdio.h> main(void) { auto int my_fun(); my_fun(); printf("Main Function</p><p>"); int my_fun() { printf("my_fun function</p><p>"); } printf("Done"); }
my_fun function Main Function Done
The above is the detailed content of In C language, nested functions. For more information, please follow other related articles on the PHP Chinese website!