Why do we need a return function in main in C?
The return value from main()
is returned to the "system" and interpreted as a process exit code which can be used in shell scripts and batch files for example. In Windows for example:
> myprogram
Hello World
> echo myprogram returned %errorlevel%
myprogram returned 0
[...] it should execute the statement after the return statement till a closing bracket is encountered?
No. A function returns when a return
is encountered (clue is in the name!) or at the closing brace - whichever occurs first. A return statement can appear anywhere in a function and a function may have more than one return statement. If the closing brace is encountered before a return
, then that is an implicit return which for a non-void function is undefined behaviour if the caller attempts to use the return value.
When you return from main()
control is returned to the system, and in a hosted environment that terminates the process and the OS recovers resources, closes files etc.