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?
- 505,946
- 29
- 409
- 696
- 11
- 1
-
3Please don't post images of text, least of all code. Copy-paste text *as text* into your question. – Some programmer dude Mar 04 '21 at 06:43
-
3_As you can see, the `main()` function does not contain the statement `return 0;`..._ No, I can see a `return 0` at line 32 (inside `main()`. :| – brc-dd Mar 04 '21 at 06:48
-
2@brc-dd Seems you're the only who looked at the image. – 273K Mar 04 '21 at 06:54
3 Answers
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.
- 380,411
- 33
- 383
- 585
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.
- 84
- 1
- 2
- 6
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
- 547
- 1
- 10