How to call the main function in C program?

C Standard LibrarySoftware & CodingComputers

In 'C', the "main" function is called by the operating system when the user runs the program and it is treated the same way as every function, it has a return type. Although you can call the main() function within itself and it is called recursion. Recursion is nothing but calling the same function by the function itself.

How Do Recursion and Function Calling Work?

You must be thinking that when the main() function calls inside main(), recursion goes on infinitely. But that is not true and it is important to know how recursion and function calling works. The function calls work with the help of PUSHING and POPPING of functions in and out from the stack respectively during execution.

The Recursion Takes Place Stack Size

Suppose there is a function, funct11() is called within main() function, the funct11() is pushed onto the stack, similarly there is another function funct22() is called by funct11, then it is pushed onto the stack and when it gets completed, POPed from the stack. The function call takes place until the stack is completely filled with the functions. This means that the recursion without a suitable condition takes place stack size times not infinite times.

The Procedure

In 'C' you can even call the main() function, which is also known as the "called function" of one program in another program, which is called "calling function"; by including the header file into the calling function. For example, if there are two programs first.c and another.c. You wish to call the main() of first.c from the body of main in another.c and pass parameters, in that case, you need to create a header file containing the function prototype at first. Finally, this header file will be included in any file that uses the function and in every .c file that you need to use the function. The compiler and linker will take care of the rest.

Published on 03-Jan-2019 07:14:26