3
votes

I know that the C++ standard says that return 0 is inserted at the end of main() if no return statement is given; however, I often see recently-written, standard-conforming C++ code that explicitly returns 0 at the end of main(). For what reasons would somebody want to explicitly return 0 if it's automatically done by the compiler?

9
Oh, the mysteries of main(). Surely it is because a good programmer doesn't assume that this rule should force him to treat main() different from 99.99% of the other code he writes. She included.Hans Passant
Hm, never thought about it like that. I guess it's sort of similar to leaving off function return types in C; I always thought that was sort of shady.Maulrus
I don't write return 0; on principle unless non-zero is a valid return value. It makes me feel like a rebel.Dennis Zickefoose
So, the accepted answer is "it just looks weird"? That pretty much proves that this is a totally subjective question.gnovice
@gnovice Are you saying it doesn't look weird?asveikau

9 Answers

10
votes

Because it just looks weird to not "return" something from a function having a non-void return type (even if the standard says it's not strictly necessary).

14
votes

By being explicit you are explicitly showing your intent.

By relying on something implicit you could have 2 cases: 1) You intended it, 2) You forgot it.

4
votes
  • Makes it clear to other programmers that you didn't just forget to put the return statement there.

  • Some compilers may issue a warning if you don't return anything.

  • Shows explicitly what the function returns.

  • Many programmers don't know about this rule.

4
votes

Misunderstanding. There's simply no reason to, and if someone doesn't know that they'll add return 0;.

4
votes

Just because your code complies with the standard, who says your code is going to be run through a compliant compiler? Believe it or not, people do use compilers besides just recent versions of GCC and Visual C++.

And of course there's the explicit intent thing that everyone else has mentioned.

3
votes

It makes behavior of the code explicit.

3
votes

Because some people don't know. Not necessarily the people who wrote that code (although that's also possible), but some people out there. Explicitly writing return 0; is being nice to them.

Also, as a convention it makes the language more uniform, which aesthetically is important to at least me.

1
votes

Because this is how they did it 30 years ago. It is more of a convention IMO.

0
votes

I often do it because I often compile code for straight C, so I either type it in out of habit or because the snippet I created main() from has the explicit return. There's no reason to remove it, so it usually stays.

Then again, there are times when I won't bother typing it in (maybe I realized I didn't need it) or I may have used a different snippet.