Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Must the int main() function return a value in all compilers? [duplicate]

Tags:

c++

turbo-c++

Why is it not necessary to include the return statement while using int main() in some compilers for C++? What about Turbo C++?

like image 954
ajarmani Avatar asked Aug 23 '13 12:08

ajarmani


People also ask

Should main () always return a value explain with example?

The return value of main() function shows how the program exited. The normal exit of program is represented by zero return value. If the code has errors, fault etc., it will be terminated by non-zero value. In C++ language, the main() function can be left without return value.

Does int main need return?

In C++, int main() can be left without a return value at which point it defaults to returning 0.

Where does int main return to?

2. int main() : It return some value like Zero or Non-Zero. The main function is C always return an integer value and it goes as an exit code to the program which executed it.

Can main return double?

Yes. According to C standard, main() should return a int value.


3 Answers

In C++, and in C99 and C11, it is a special rule of the language that if the control flow reaches the end of the main function, then the function impliclty returns 0.

like image 123
Kerrek SB Avatar answered Oct 28 '22 07:10

Kerrek SB


In C++ and C99/C11, without a return statement in main function, it's default to return 0;

§ 3.6.1 Main function

A return statement in main has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling std::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;

also read wiki page C/C++ main function

In case a return value is not defined by the programmer, an implicit return 0; at the end of the main() function is inserted by the compiler; this behavior is required by the C++ standard.

like image 32
billz Avatar answered Oct 28 '22 07:10

billz


main must return an int, some compilers, including Turbo C++, may allow other return values, notably void main, but it's wrong, never use that.

However in C++, if you don't explicitly return a value in main, it's the same as return 0;

C++11 §3.6.1 Main function section 5

A return statement in main has the effect of leaving the main function (destroying any objects with automatic storage duration) and calling std::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;

Note that for C, this is only supported in C99 and later, but not supported by C89.

like image 22
Yu Hao Avatar answered Oct 28 '22 08:10

Yu Hao