Getting to know the main function

Getting to know the main function

Each C++ program contains multiple functions, but it must contain a function named main , and the operating system runs the C++ program by calling the main function. The main function is like a door of the program. Without this door, the program cannot be entered, so a C++ program must contain the main function

In general, a function definition consists of four parts:

  • return type
  • function name
  • parameter list
  • function body
//main函数的定义

int main(void)
{
    return 0;
}

/*
* 函数定义的一般模板:
* 返回类型 函数名(形参列表)
* {
*   函数体
* }
*/

Although the main function is special compared to other functions, its definition is consistent with other functions, which will be introduced in detail below:

  1. It is stipulated that the return type of the main function must be an integer (int) . There are many built-in data types (types defined by the language itself) in C++, and int is one of them. In future studies, we can also customize data types as needed.

An important concept is mentioned here: Type
Type is one of the most basic concepts of program design. The data processed by the program is stored in variables, and each variable has its own type. A type not only defines the The content also defines the operations that can be performed on this type of data

  1. In the above example, the formal parameter list of main is empty (void), that is, the function has no formal parameters, and its form is equivalent to writing nothing in the parentheses
int main()
  1. A function body is a block of statements that begins with an opening curly brace and ends with a closing curly brace
{
    return 0;
}

The only statement in this statement block is return, which ends the execution of the function. It is worth noting that when the return statement returns a value, the type of the return value must be consistent with the return type of the function. For example, the return type of the main function is integer, and the 0 returned by return is also an integer

Note:
Most C++ statements end with a semicolon, and they are easily ignored. If you forget to write a semicolon, it will often cause inexplicable compilation errors

Guess you like

Origin blog.csdn.net/m0_50275697/article/details/131301668