c++undefined-behavior

Not returning from a function is not an error?


What's the reasoning that for most major compilers, gcc, clang, nvc produce only a warning while compiling following code (suppressable one).

#include <iostream>

int foo() { return 42; }   
int boo() { foo(); }

int main()
{
    std::cout << boo() << std::endl;
}

We just had incidents that barely didn't end in a human life losses by pure luck because that and such code was a part of hardware vendor code (an autopilot to be precise) which we couldn't change. The particular compiler didn't even produce a warning (only in such case when there is only a return in function). The original's reasoning that {foo();} is an expression doesn't make sense, but I have hard time explain it to overseers.

More strange, in other cases compilers produce errors if there is nor eturn. Only compiler that diagnoses a error in this case is MSVC (practically any version).


Solution

  • The problem is that the compiler needs to consider everything.

    Small change:

    int foo() { throw 42; }   
    int boo() { foo(); }
    

    Unusual, but entirely legal. There's no "missing return statement" in foo, but you need to know that foo always throws.

    The idea isn't entirely far-fetched. If foo was called log_and_throw<Exc>, you'd expect it to never return normally.