Thursday, January 21, 2016

Calling main() from main() in c/c++

Many people think that when the main() function call inside the main(), recursion goes on infinite times. But it is not true as such so is it possible to call main() from main inside.?

Yes, we can call the main() within the main() function. The process of calling a function by the function itself is known as Recursion. Well, you can call a main() within the main() function .

The function calls take place until the stack overflow occurs, that is until the stack is completely filled with the functions. This implies that the recursion without a suitable condition takes place not infinite times but stack size times.So that particular experiment when conducted, compiles successfully but it suffers from a run time error or illegal instruction. So you should have a condition that does not call the main() function to terminate the program. Otherwise,the program will never return and run infinitely.

In first example global variable c=0 declared (bcz when main() called is should not reintialized) and after print statement first time it will print 1 (c+1)and condition will true so after calling main it will print 1 now condition will false so program will exit.

#include"stdio.h"
#include"conio.h"
int c=0;
void main(){
       clrscr();
       printf("Before main : %d",c);
       c++;
       if(c<2){
       main();
       exit(0);
       }
       getch();
}

--------------------------------------------------------------------------------------
int main() {
    cout << "Hello World" << endl;
    system("pause");//for pause program execution
    return main();
}