tags:

views:

153

answers:

3

I'm newly using CODE::BLOCKS+mingw compiler If I don't type return 0 at the end of program,I can see that main() is returning some integer,I learnt that main() returning 0 infers program executes successfully.I don't find any flaw in my code, why is it returning some integer?

secondly any function returns its value to its function call, to where does main() return its value?

+3  A: 

The C++ Standard says that if you don't explicitly return a value, the compiler must generate code as if you had typed:

return 0;

Exactly what the return value means and how it is returned is implementation specific. For most OSs, the return value becomes the exit code of the process.

anon
This only holds for C++; which wasn't explicitly defined as the language being used.
Williham Totland
@Williham The question is tagged "C++"
anon
It is also tagged "C". And since this issue arises, he is clearly not using a C++ compiler at any rate. (At least not a compliant one.)
Williham Totland
@Williham: there is similar language in n1256: " **5.1.2.2.3 Program termination** 1 If the return type of the main function is a type compatible with int, a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument;10) *reaching the } that terminates the main function returns a value of 0*. If the return type is not compatible with int, the termination status returned to the host environment is unspecified." Emphasis added.
John Bode
This still implies minGW isn't completely up to speed on that bit, irrespective of language.
Williham Totland
+1  A: 

main() returns its value to the system (tho' indirectly, and let's not embark upon a discussion of this point at present).

When control reaches the end of a function with a return value (such as, say, main(); what will be returned is whatever is already in the register destined to hold the return value (this is sometimes the value of the last statement, sometimes not).

The moral, of course, is that you should always end your main with return 0;

Williham Totland
+2  A: 

main() returns its value to the system. The system can then use this as an error or success code. In Linux you can do this:

 $ yourprog && someotherprog

And it will run yourprog, and then someotherprog, if and only if yourprog returned 0.

In Windows you can use the if errorlevel idiom in batch scripts to check a program's return value.

Also, if you start a process from another (with fork() or CreateProcess() or something) you can later retrieve its exit status and act accordingly.

Martinho Fernandes