Why return 0?

Why do you have to place
return 0;
at the end of your code?
what is it's purpose?
Technically, in C or C++ main function has to return a value because it is declared as "int main"
which means "main function should return integer data type"

if main is declared like "void main", then there's no need of return 0.

Some compilers even accept and compile the code even if u dont write return 0. varies from compiler to compiler
void main is not allowed by the C++ standard (nor the C standard) and should not even compile.
The int value that main returns is usually the value that will be passed back to the operating system. 0 traditionally indicates that the program was successful.
You don't have to return 0 explicitly, because that'll happen automatically when main terminates. But it's important to keep in mind that main is the only function where omitting return is allowed.
Athar wrote:
But it's important to keep in mind that main is the only function where omitting return is allowed.

That's not entirely correct. Functions whose return type is void are allowed to ommit the return keyword as well.
Last edited on
That's not entirely correct. Functions whose return type is void are allowed to ommit the return keyword as well.

Make that "functions that actually return something other than main".
1
2
3
4
5
6
if (program_executed_fine)
return 0;

else if (program_had_error)
return 1;


return 0 means that your program executed without errors.
Last edited on
Thanks all for the fast reply's!
I guess my compiler can do it without since i didn't used before i saw it in other scripts!
It's good practice to use it. AngelHoof shows why. It reports any errors back to the environment in which it was run.
A return value just ends the life of a variable or function return 0; simply ends everything you can also do return main();(well I think it works that way).
Last edited on
return main(); will most likely cause a crash. It makes no sense unless main() is designed to be strangely recursive. Which would be terrible design.
Last edited on
closed account (jwC5fSEw)
I'd just like to add to what some people have said: a compiler can be expected to implicitly add return 0 to main() because ISO C++ demands it (though I don't believe the same can be said for ISO C). Any compiler that doesn't is not standards-compliant.
Last edited on
@clover leaf,
You seem to be confusing a return statement to the end of a block:
1
2
3
4
5
6
int x = 0;

{
        int y = 0;
}
/* y no longer exists */
Topic archived. No new replies allowed.