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

In C language, nested functions

WBOY
Release: 2023-09-06 13:57:06
forward
1220 people have browsed it

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();
}
Copy after login

Output

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

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");
}
Copy after login

Output

my_fun function
Main Function
Done
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template