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: 
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.
Use the [-Wall](https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wall) flag in [GCC](https://en.wikipedia.org/wiki/GNU_Compiler_Collection).

> 
> warning: control reaches end of non-void function
> 
> 
> 

Or more specifically, [-Wreturn-type](https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wno-return-type).