Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

1 Answer
karthikeya Boyini

In some applications, we have seen that some functions are declared inside another function. This is sometimes known as nested function, but actually this is not the nested function. This is called the lexical scoping. Lexical scoping is not valid in C because the compiler is unable to reach correct memory location of inner function.

Nested function definitions cannot access local variables of surrounding blocks. They can access only global variables. In C there are two nested scopes the local and the global. So nested function has some limited use. If we want to create nested function like below, it will generate error.

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'

But an extension of GNU C compiler allows declaration of the nested function. For this we have to add auto keyword before the declaration of nested function.

Example

#include <stdio.h>
main(void) {
   auto int my_fun();
   my_fun();
   printf("Main Function\n");
   int my_fun() {
      printf("my_fun function\n");
   }
   printf("Done");
}

Output

my_fun function
Main Function
Done

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.