Department of Engineering

IT Services

C++ and the main function

Nothing on this page is crucial to your understanding of C++, and may well confuse you if you're learning C++. However people ask about these issues (and interviewers ask about them!), so here are some comments.

The function called main in a C++ program is a special case. According to the C++ standard, you're not allowed to call it directly. Also

  • The books say it's where execution begins, so every C++ program needs one somewhere.
  • Although it's supposed to return an int, you're allowed to return nothing (with other functions that return an int, you're likely to be warned if you don't return one)

Both of these issues merit further discussion

main is where execution begins ...

Here's a minimal, legal C++ program.

int main(){}

It's true that all C++ programs need a main function, but consider the following program. It defines a new type of variable whose constructor prints something out. An object of this type is created outside of an empty main function. If you run the program you'll see that the text is printed out even though the main function is still empty.

#include <iostream>
using namespace std;

class newtype {
  newtype() { cout << "Not in main!" << endl; }

newtype i;

int main(){}

So main isn't always the first function called. Indeed, the constructor could call other functions and then end by doing an exit thus bypassing main entirely.

main is allowed to return nothing

As we've seen,

int main(){}

is legal. It's worth wondering where any returned value might go. Compile this

int main() { return 6; }

If you run it from the Unix command line you'll see nothing, but if you then type

echo $?

you'll see the 6 is printed out - i.e. the value returned from main can be accessed by Unix. This is useful if Unix wants to know whether a C++ program ran successfully. A return value of 0 is taken to mean success. Anything else means failure