Home  >  Article  >  Backend Development  >  In C language, nested functions

In C language, nested functions

WBOY
WBOYforward
2023-09-06 13:57:061194browse

In C language, nested functions

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.

Example

#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();
}

Output

text.c:(.text+0x1a): undefined reference to `my_fun2&#39;

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.

Example

#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");
}

Output

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete