Why does a C++ function that returns a numeric value such as int
or double
work just fine if I don't include the return statement?
Should I avoid that even though the program runs fine?
Thanks
Asked
Active
Viewed 67 times
0

Abdulaziz Asiri
- 93
- 1
- 7
-
1How did you check that it works fine? And yes, you should avoid such as thing and you will get some warnings from the compiler. – MikeCAT Nov 26 '15 at 14:22
-
I guess because it compiles and runs. – Abdulaziz Asiri Nov 26 '15 at 14:24
-
1Your questions have already been answered : [link](http://stackoverflow.com/questions/1610030/why-can-you-return-from-a-non-void-function-without-returning-a-value-without-pr) – SwissFr Nov 26 '15 at 14:24
1 Answers
3
It could "work fine" for two reasons:
- Your function is not
main()
, in which case flowing off the end with no return statement causes undefined behaviour1, and it just happens that it seems to work fine. But it doesn't really. - The function is
main()
, which has an implicitreturn 0;
.
For case 1, you should consider your code badly broken and fix it.
1 §6.3.3 [stmt.return] in the C++11 standard

juanchopanza
- 223,364
- 34
- 402
- 480
-
Nice answer! Maybe also just worth adding a little note about how `main` can omit the return statement (just for completeness). – Nov 26 '15 at 14:23
-
@Ike implicitly it is there, because return value of main isnt used – 463035818_is_not_an_ai Nov 26 '15 at 14:24
-
-
1
-
-
1"Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function." _§6.3.3_ – masoud Nov 26 '15 at 14:37