Search code examples
c++creturn-valuelanguage-lawyercompiler-flags

Why isn't there any compiler error when a return statement is not present?


Unlike Java, in C/C++ the following is allowed:

int* foo ()
{
  if(x)
    return p;

  // What if control reaches here?
}

This often causes crashes and it is hard to debug problems. Why doesn't the standard enforce to have a final return for non-void functions? (Compilers generate an error for a wrong return value.)

Is there a flag in GCC or MSVC to enforce this? (something like -Wunused-result)


Solution

  • It is not allowed (undefined behaviour). However, the standard does not require a diagnostic in this case.

    The standard doesn't require the last statement to be return because of code like this:

    while (true) {
      if (condition) return 0;
    }
    

    This always returns 0, but a dumb compiler cannot see it. Note that the standard does not mandate smart compilers. A return statement after the while block would be a waste which a dumb compiler would not be able to optimise out. The standard does not want to require the programmer to write waste code just to satisfy a dumb compiler.

    g++ -Wall is smart enough to emit a diagnostic on my machine.