Mohit Jain
Mohit Jain

Reputation: 43959

where does main() return its value?

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?

Upvotes: 4

Views: 2227

Answers (4)

Rohan Mundhey
Rohan Mundhey

Reputation: 15

main() returns it's value to the loader(system). it indicated wether the program executed sucessfully or not. return(0); indicates success as SUCCESS IS UNDEFINED :D !!!

Upvotes: 0

R. Martinho Fernandes
R. Martinho Fernandes

Reputation: 234654

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.

Upvotes: 4

Williham Totland
Williham Totland

Reputation: 29039

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;

Upvotes: 2

anon
anon

Reputation:

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.

Upvotes: 11

Related Questions