This blog is under construction

Tuesday, 31 December 2013

Nested function in C

What is nested function?
If a function is defined inside another function, then it is called as nested function. 

Nested function example in C:
Consider the following example,
int add(int a, int b) {
       void print(int res) {
         printf("Result is %d, res);
      }
      print(a+b);
      return 0;
}

Here, print() is a nested function.  Because, it is defined inside another function named add().

Example C program using nested functions:
 
  #include <stdio.h>
  void add(int a, int b) {
        void print(int res) {  // nested function
                printf("Result is %d\n", res);
                return;
        }
        print(a + b);  // passing sum of a and b as parameter
        return;
  }

  int main() {
        add(10, 20);
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Result is 30



No comments:

Post a Comment