Question: 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](https://en.wikipedia.org/wiki/Microsoft_Visual_C%2B%2B) to enforce this? (something like `-Wunused-result`)

Answer: 
You can convert the warning into an error by using the following compiler options 

`-Wreturn-type -Werror=return-type`. 

Check out This [link](https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html)
The obvious answer is: because it's not an error. It's only an error if
`x` is false and if the caller uses the return value, neither of which
can necessarily be determined by the compiler, at least in the general
case.

In this particular case (returning a pointer), it wouldn't be too
difficult to require a `return` for all paths; Java does this. In
general, however, it's not reasonable in C++ to require this, since in
C++, you can return user defined types for which it may be impossible to
construct a value (no default constructor, etc.) So we have the
situation where the programmer might not be able to provide a `return`
in a branch that he or she knows can't be taken, and the compiler can't
determine that the branch can't be taken.

Most compilers will warn in such cases, when it can determine the flow.
All of the ones I've seen also warn in some cases where it's clearly
impossible to fall off the end, however. (Both g++ and VC++ warn about:

```
int
bar( char ch )
{
    switch ( ch & 0xC0 ) {
    case 0x00:
    case 0x40:
        return 0;

    case 0x80:
        return -1;

    case 0xC0:
        return 1;
    }
}

```

, at least with the usual options. Although it's quite clear that this
function never falls off the end.)