3 minute read

Introduction

The main function is the entry point of a C++ program. It’s where the execution of a program starts. The main function is a special function in C++, and it’s the only function that the operating system looks for and executes when the program starts. In this tutorial, we will learn about the main function and what should it return.

The main function signature

The main function has a special signature in C++. It can have one of the following forms:

int main() {
    // code here
}

int main(int argc, char* argv[]) {
    // code here
}

int main(int argc, char** argv) {
    // code here
}

The first form is the simplest and the most common. It doesn’t take any arguments and returns an integer. The second and third forms take two arguments, argc and argv. The argc argument is the number of arguments passed to the program, and argv is an array of strings that contains the arguments passed to the program. The return value of main

The main function should return an integer. This integer is called the “exit status” of the program, and it is returned to the operating system. A return value of 0 indicates that the program has executed successfully, and any other value indicates that an error has occurred.

It’s important to note that the main function can return without an explicit return statement. In this case, the compiler will automatically insert a return 0 at the end of the main function.

Example

int main() {
    // code here
    return 0;
}

or

int main() {
    // code here
}

In the example above, the main function doesn’t take any argument and it returns 0 indicating the successful execution of the program.It’s also worth mentioning that, although it’s not required, it’s a good practice to include a return statement in the main function, even if it’s just return 0;. This can make it clearer to other developers that the program is intended to exit successfully, and it also makes it easier to add error handling later on.

Conclusion

In this tutorial, we have learned about the main function in C++, its signature and its return value. We saw that the main function can have three forms, the simplest one is the one without arguments and returns an integer. The return value of the main function is called the “exit status” of the program, which indicates whether the program has executed successfully or not. A return value of 0 indicates success and any other value indicates an error. It’s a good practice to include a return statement in the main function, even if it’s just return 0; to make it clear that the program is intended to exit successfully. Understanding the main function and its return value is an essential part of mastering the C++ programming language.

References

Read more about the main function on the C++ documentation here: https://en.cppreference.com/w/cpp/language/main_function