main() Function

The main() function is the entry point of any C++ program. It is where program execution begins. Every C++ program must have one main() function. When you run a C++ program, the control is transferred to the main() function, and the instructions inside it are executed sequentially.


Syntax

The syntax of main() function in C++ language is:

</>
Copy
int main() {
    // Code statements
    return 0;
}
int
The return type of the main() function. It returns an integer value to the operating system.
main()
The name of the function. It serves as the entry point of the program.
return 0;
Indicates successful execution of the program. A non-zero return value indicates an error or abnormal termination.

The syntax of main() function follows the syntax of a regular function in C++.


Examples

Example 1: Basic main() Function

In this example, we will write a simple main() function that prints a message to the console.

</>
Copy
#include <iostream>
using namespace std;

int main() {
    cout << "Hello, World!" << endl;
    return 0;
}

Output

Hello, World!

Explanation

  1. #include <iostream>: Includes the input-output stream library for using cout.
  2. int main(): Defines the entry point of the program.
  3. cout << "Hello, World!" << endl;: Prints “Hello, World!” to the console and moves to a new line.
  4. return 0;: Indicates that the program executed successfully.

Example 2: Using Command-Line Arguments in main()

In this example, we will show how to use command-line arguments in the main() function.

example.cpp

</>
Copy
#include <iostream>
using namespace std;

int main(int argc, char* argv[]) {
    cout << "Number of arguments: " << argc << endl;
    for (int i = 0; i < argc; ++i) {
        cout << "Argument " << i << ": " << argv[i] << endl;
    }
    return 0;
}

Output

Number of arguments: 3
Argument 0: ./example
Argument 1: arg1
Argument 2: arg2

Explanation

  1. int main(int argc, char* argv[]): A version of main() that accepts command-line arguments.
  2. argc: An integer representing the number of arguments passed to the program, including the program name.
  3. argv: An array of C-style strings (character pointers) containing the command-line arguments.
  4. for (int i = 0; i < argc; ++i): Iterates through the command-line arguments and prints each one to the console.
  5. argv[0]: Represents the name of the program.
  6. Other elements of argv represent the additional arguments passed to the program.

Important Points about main() function

  1. Every C++ program must have a main() function, as it is the starting point of the program.
  2. The main() function can optionally accept command-line arguments for additional functionality.
  3. The return 0; statement is used to indicate successful execution. A non-zero return value signifies an error.