-
To understand main(), you first need to understand what a function means in C.Anything followed by () is called a function. A function, in simple words is a part of program dedicated for a purpose. Now let us assume that you are writing a program to make a simple calculator. It will be able to add, subtract,multiply,divide etc.
-
You can make a linear program
cout<<”Enter 2 nos”;
cin>>x>>y;
cout<<”sum:”<<x+y;
cout<<”Difference:”<<x-y;
//and so on
Or you can make a well structured program using functions. Given below is an example for an add function:
int add(int x,int y)
{
return x+y;
}
Now you can just 'call' this function anywhere in your program as you have already set the logic for addition. You do not have to write the code again. You used the functionality of add() function.
-
Now coming to what a main() function is: In C, the "main" function is treated the same as every function, it has a return type (and in some cases accepts inputs via parameters).
-
The only difference is that the main function is "called" by the operating system when the user runs the program. Thus the main function is always the first code executed when a program starts.
int
// the main function will usually returns a 0 if successful
main()
// this is the name, in this case: main
{
// this is the body of the function (lots of code can go here)
}
-
main() defines an entry point in an application entry point in C. An entry point is a function that is executed by the loader when a program is started. Therefore main is where our program starts.
-
In C main takes the arguments argc and argv, which hold all the command line parameters supplier when the program was started, and main returns an integer, the exit status of the program which tells the caller if there were any problems.
-
You must've noticed that previous example of funtions(add()) was user defined i.e the programmer has told the computer, what to do in case the function is called. But nobody told the computer what to do in case main() is called. It is pre-defined in the C language that the purpose of main is to start execution. To be honest, main() doesn't have to do anything other than be present in your C code.Eventually, it contains instructions that tell the computer to carry out whatever task your program is designed to do, but those tasks are also specified by the programmer.