Wednesday, November 8, 2006

C++ / C: Should main ( ) return void?

The answer is 'NO'. 'void' has never been the return type of main() in C++ and nor C. You should return 'int'. Example,

int main ( ) {
    std::cout<< "Hello Mama";
    return 0;

What does 'The C++ Standard' say?

Let me quote 'The C++ Standard' here

3.6.1 Main function


2 An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation-defined. All implementations shall allow both of the following definitions of main:

int main() { /* ... */ }


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

.... and it continues to add ...

5 A return statement in main has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling exit with the return value as the argument. If control reaches the end of main without encountering a return statement, the effect is that of executing return 0;

So, now you know what the standard states. Shun the books that don't understand the standard properly.

No comments: