5

I am surprised that a file containing the following lines of code is successfully compiled and linker produces an executable. I thought that all functions, except main, must have a valid return statement unless the return type is void.

int foo(){}
double bar(){}
int main(){}

What am I missing?

R Sahu
  • 204,454
  • 14
  • 159
  • 270

2 Answers2

8

Not returning a value from a function that says it does is undefined behavior. It compiles and links, but don't expect the program to behave correctly.

If you compile with a high warning level, the compiler will tell you about it.

  • I thinker Cpp should let virtual functions and callbacks have a default return value specified by the server of the callback. Example, void onCall() def_return (-1) so that the server is guaranteed to have a proper return value. – user13947194 Jun 11 '22 at 01:43
4

I thought that all functions, except main must have a valid return statement unless the return type is void.

Yes, they must. You'll get undefined behaviour if they don't.

What am I missing?

If the function is sufficiently complicated, it can be difficult or impossible for the compiler to tell whether all return paths return a value; so the compiler isn't required to diagnose the error.

Most compilers will issue warnings in many cases, if you enable warnings.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • 1
    I find this to be an excellent use case for a static analyzer. –  Mar 06 '14 at 19:51
  • @faranwath: Indeed; although a good compiler should include that analysis, and it's not always possible to detect statically. – Mike Seymour Mar 06 '14 at 19:52
  • 2
    I find you last comment interesting. Care to share an example? I cannot think of a plausible situation from the top of my mind. –  Mar 06 '14 at 19:55
  • 1
    @faranwath: For example, a `switch` statement with a `return` in each branch, where you (but not the compiler) can prove that the value can only be one of the handled cases. On a tiny embedded system, you might not want the overhead of handling the (theoretically impossible) default case. – Mike Seymour Mar 06 '14 at 20:08
  • 3
    @faranwath: More abstractly, tracing all possible return paths is equivalent to solving the halting problem, which is well known to be impossible to solve statically in the general case. – Mike Seymour Mar 06 '14 at 20:12
  • I see it better now with the analogy you provided. Thanks! –  Mar 06 '14 at 20:14