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.
My guess: Because sometimes the programmer knows better than the compiler. With this simple example, it's clear that someting is wrong, but consider a switch of many values, or many checks in general. You, as the coder, *know* that certain values just will not be passed in to the function, but the compiler doesn't and just hints you, that there might be something wrong.

```
#include <iostream>

int foo(){
    if(false)
        return 5;
}

int main(){
    int i = foo();
    std::cout << i;
}

```

Note that [even warning level 1](http://msdn.microsoft.com/en-us/library/6deaf4k9.aspx) on MSVC gives the following warning:

> 
> warning C4715: 'foo' : not all control paths return a value
> 
> 
>