Nested functions in C


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
");    int my_fun() {       printf("my_fun function
");    }    printf("Done"); }

Output

my_fun function
Main Function
Done

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements