when should i use "return 0;" at the end of a main() function?

Recommended Answers

All 2 Replies

Unless you're using void main() (which is not advisable to use), the return type of your main() is int, so you either return 0(which indicates successful run of the program)or 1 or any other int value(which indicates failure) i.e if your program runs successfully, then 0 is returned , else, any other value you specified is returned.

Please,if my reply satisfied your problem, can you kindly add to my reputation? Thanks!!

commented: Begging for rep is unbecoming. -4

>when should i use "return 0;" at the end of a main() function?
Always or never, depending on your preference and whether or not you're writing standard C++. In standard C++ 0 is returned automagically when execution falls off the end of main, so the following is perfectly valid:

int main()
{
}

However, some people like to be consistent and explicitly return from any function that doesn't return void:

int main()
{
  return 0;
}

My personal preference is that if I have multiple returns from main, EXIT_SUCCESS is always explicit at the end, but otherwise I omit the return statement entirely:

int main()
{
  // Stuff with no return statement
}
#include <cstdlib>

int main()
{
  // Stuff

  if ( failed )
    return EXIT_FAILURE;

  // Stuff

  return EXIT_SUCCESS;
}
commented: Nicely said. +0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.