-5

image

As you can see, the main() function does not contain the statement return 0;. But the program can still execute normally, even though the main() function has been specified to return a value of int. I just don't understand why. Could you please explain it?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770

3 Answers3

3

The main function is treated differently by the compiler. If there's no return 0; at the end then the compiler will implicitly add such a statement.

Note that this is only for the main function, you can't omit return statements in any other function.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

In your attached image the main function does have a return statement.

Anyways if you don't include a return statement for main, the compiler will do that for you implicitly during compilation process. Although it is a good practice that we include one!

Similarly, even if you don't have a default non-parameterized constructor, a compiler will also include one, with empty body.

Viraj Jadhav
  • 84
  • 1
  • 2
  • 6
0

In C++ :

If control reaches the end of the main function, return 0; is executed.

which is equivalent to first leaving the function normally (which destroys the objects with automatic storage duration) and then calling std::exit with the same argument as the argument of the return. (std::exit then destroys static objects and terminates the program)

in C:

If the return statement is used, the return value is used as the argument to the implicit call to exit() (see below for details). The values zero and EXIT_SUCCESS indicate successful termination, the value EXIT_FAILURE indicates unsuccessful termination

From cppreference

User
  • 572
  • 2
  • 10