Skip to main content

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



Comments

Popular posts from this blog

restorecrtmode example in c

Header file:     graphics.h Synopsis:        void restorecrtmode();       Description:       restorecrtmode() restores screen mode to text mode. restorecrtmode function in c graphics   #include <graphics.h>   #include <stdlib.h>   #include <stdio.h>   #include <conio.h>   int main(void) {         /* request auto detection */         int gd = DETECT, gmode, err;         int midx, midy;         /* initialize graphics and local variables */         initgraph(&gd, &gmode, "C:/TURBOC3/BGI");         /* read result of initialization */         err = graphresult();         if (err != grOk) {                 /* an error occurred */               ...