main() function in C++

In this tutorial, we are going to learn about the main() function in C++. As you know, in almost every C++ program there is a main() function and every other function is called or implemented through main(). Therefore, it becomes important to understand the proper use of main() function in your program.

main() function in C++

main() function is an entry point for a C++ program. We give the system access to our C++ code through the main() function.

Syntax of main() function:

A main() function declaration can be done in the following ways.

int main() {}

or

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

or

int main(int argc, char* argv[], /*other parameters*/) {}

 

Although some compilers may allow the use of void main(){} or main(){}, it is not as per the standard and hence should be avoided. The main() function must always return an integer.

See the example code for main() function given below.

#include <iostream>
using namespace std;

int main()
{
     cout<< "This is from main() function.";
     return 0;
}

The program prints:

This is from main() function.

Now see this example to understand what happens when a function cannot be accessed through the main() function.

#include <iostream>
using namespace std;
int function();
int fun()
{
     cout<< "This is not from main() function.";
     return 0;
}

fun();

int main()
{
     cout<< "This is from main() function.";
     return 0;
}

The compiler throws an error here because fun() is not accessible to the main() function. The execution begins in main() function and ends with the return statement without invoking the function fun().

Now if we keep the function call inside the main() function, the compiler throws no error. See the implementation.

#include <iostream>
using namespace std; 
int function();
int function() 
{ 
    cout<< "This is not from main() function."; 
    return 0; 
}

int main()
{
    cout<< "This is from main() function.\n";
    function();
    return 0;
}

The output of the above code is:

This is from main() function.
This is not from main() function.

Note: Creating an instance of a class and invoking its methods must also be done in main() function or in a function/class that can be accessed by main() function.

For the use of parameters in the main() function, refer here: Command Line Arguments in C++

Leave a Reply

Your email address will not be published. Required fields are marked *