Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Proper Declaration of main in C++



The main() function is the entry point of every C++ program where execution begins. It is invoked automatically when the program is executed. The main() function returns the execution status to the operating system (indicating whether the program executed successfully or not). You can also use optional command-line arguments, argc and argv, to pass values to the program.

Declaration /Prototype of main() 

The standard prototype of main() function is as follows:

int main()
{ body }

Or,

int main(int argc, char *argv[])
{ body }

Here,

  • argc : Number of arguments passed to the program from the environment where program runs.
  • argv : This is pointer to the first element of an array.

Example of C++ main() Function

This is a basic C++ program where the main() function uses no argument to print the result. Here, we simply display the sum of two numbers.

#include <iostream>
using namespace std;
int sum(int x, int y) {
   int s = x + y;
   cout << "The sum of numbers : " << s;
   return s;
}
int main() {
   sum(28, 8);
   return 0;
}

Output

The above program produces the following result:

The sum of numbers : 36

Example of C++ main() Function with Arguments

In this C++ example, we print the total number of command-line arguments and also print each argument using a loop with argv.

#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

The above program produces the following result:

Number of arguments: 1
Argument 0: main
Updated on: 2025-04-21T18:39:38+05:30

127 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements