Why return 0?

May 30, 2010 at 3:09pm
Why do you have to place
return 0;
at the end of your code?
what is it's purpose?
May 30, 2010 at 3:17pm
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
May 30, 2010 at 4:09pm
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.
May 30, 2010 at 4:18pm
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 May 30, 2010 at 4:19pm
May 30, 2010 at 4:21pm
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".
May 30, 2010 at 4:22pm
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 May 30, 2010 at 4:23pm
May 30, 2010 at 4:44pm
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!
May 30, 2010 at 4:50pm
It's good practice to use it. AngelHoof shows why. It reports any errors back to the environment in which it was run.
May 31, 2010 at 6:42am
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 May 31, 2010 at 6:43am
May 31, 2010 at 8:13am
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 May 31, 2010 at 8:15am
Jun 1, 2010 at 12:01am
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 Jun 1, 2010 at 12:01am
Jun 1, 2010 at 12:20am
@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.