|
|
|||
![]() |
Department of Engineering |
| University of Cambridge > Engineering Department > computing help > Languages > C++ |
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
Both of these issues merit further discussion
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 {
public:
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.
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
| | C++ | Languages | computing help | |