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
#include <iostream>
: Includes the input-output stream library for usingcout
.int main()
: Defines the entry point of the program.cout << "Hello, World!" << endl;
: Prints “Hello, World!” to the console and moves to a new line.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
int main(int argc, char* argv[])
: A version ofmain()
that accepts command-line arguments.argc
: An integer representing the number of arguments passed to the program, including the program name.argv
: An array of C-style strings (character pointers) containing the command-line arguments.for (int i = 0; i < argc; ++i)
: Iterates through the command-line arguments and prints each one to the console.argv[0]
: Represents the name of the program.- Other elements of
argv
represent the additional arguments passed to the program.
Important Points about main() function
- Every C++ program must have a
main()
function, as it is the starting point of the program. - The
main()
function can optionally accept command-line arguments for additional functionality. - The
return 0;
statement is used to indicate successful execution. A non-zero return value signifies an error.