Each C + + program contains one or more functions (function), in which the name of one function must be main. A function consists of a series of statements (statement) that perform function functions. The operating system executes the program by calling the main function. This function executes its constituent statement and returns a value to the operating system.
The following is a simple main function that does not return a value:
int main ()
{
return 0;
}
The operating system uses the value returned by the main function to determine whether the program was successfully executed or failed. The return of 0 indicates success.
The main function is very special, the most important of which is that the function must exist in every C + + program, and it is the only function that the operating system explicitly calls.
We define the main function in the same way that we define other functions. The function definition illustrates four parts: The return type, the function name, the list of arguments in parentheses (possibly empty), and the body of the function. The main function may contain a set of parameters. In the definition above, the argument list is empty.
The main function above requires an int type return type, which represents an integral type. The integral type is a built-in (built-in) type, which means that this type is defined by the language.
The last part of the function definition (the body of the function) is a set of statement blocks that begin with a wave parenthesis (curly brace), ending with a wavy parenthesis:
{
return 0;
}
The only statement in our program is return, which is the statement used to terminate the function.
Attention
Note the semicolon after the return statement. In C + +, semicolons mark the end of most statements. They are easy to ignore if they forget compiler error messages that can lead to incomprehensible.
When return contains a value (for example, 0), this value is the returned value of the function. The type of the return value must be the same as the return type of the function or must be able to be converted to that type. In the example, the return type of main is an integral type, and the value 0 is an integral type.
In most systems, the return value of main is the status identifier. A return value of 0 indicates that main was executed successfully. The meaning of other return values is defined by the operating system. Usually a return value of not 0 indicates an error has occurred. Each operating system is by itself a way to tell the user that the main function returns a value.