What is the use of main() in c ?

The basic main() function
When the operating system runs a program in C, it passes control of the computer over to that program. This is like the captain of a huge ocean liner handing you the wheel. Aside from any fears that may induce, the key point is that the operating system needs to know where inside your program the control needs to be passed. In the case of a C language program, it's the main() function that the operating system is looking for.

At a minimum, the main() function looks like this:

main() {}
Like all C language functions, first comes the function's name, main, then comes a set of parentheses, and finally comes a set of braces, also called curly braces.

If your C program contains only this line of code, you can run it. It won't do anything, but that's perfect because the program doesn't tell the computer to do anything. Even so, the operating system found the main() function and was able to pass control to that function — which did nothing but immediately return control right back to the operating system. It's a perfect, flawless program.
 
The use of main() function in c :
This important block of c where execution is done if you don't put your code within this main function your codes will not be executed. Example:

Codes written not in main() block will surely execute
:
main ()
{
int a=2,b=3,sum;
printf("%d",sum);
getch();
}


Codes written within main() block will not execute
:

int a=2,b=3,sum;
printf("%d",sum);
getch();
 
The only difference is that the main function is "called" by the operating system when the user runs the program.
 
In C main function has to return a value because it is declared as "int main" which means main function should return "integer main data type". If main is declared like "void main", then no need of returns 0.
 
The function main() is, in fact, called. But it is not called explicitly; the call is implicit. Which means that you do not have to write that call into your program, it is done automatically by the run-time environment.

In other words, when you compile a C program, the actual code generated by the compiler begins with a preamble that sets up memory, configures standard input and output, and does a few other housekeeping chores, followed by a call to the main() function, followed by clean-up and termination code.

If you were to try to compile a program with no main() function, the linker would actually complain about its absence, because it is referenced in the run-time environment.
 
Last edited:
Main() is the default entry point of a C and C++ program. The correct signature of the function is:

int main(int argc, char **argv, char **envp);

and in C++ it's treated as a special case, defined automatically as extern "C" to keep the symbol name free from name mangling.
 
Back
Top