Search code examples
c++c++11cross-compilingportability

Don't need a return after throw - standard or compiler specific?


If I have function like this

int f()
{
   //something
   if ()
   {
      //something
      return 1;
   }

   throw std::runtime_error("msg");
}

In Visual studio in compiles ok and works as expected, but is it a standard thing that after throw I don't need a return statement, or it can lead to some error on other compilers?


Solution

  • You are missing one important detail, and this is: Also this would compile without compiler errors

    int f_wrong() {}  // Wrong!
    

    It does not produce a compiler error, but calling the function invokes undefined behavior.

    Also this is "ok-ish" when it is never called with a false parameter:

    int f_still_wrong(bool x) {  
         if(x) return 42;
    } 
    

    Generally we want to write code that cannot cause undefined behavior at runtime. The compiler warning you get when a function is missing a return can help with that.

    That being said, what matters is whether there is a path the falls of the end of the function without returning. In the case of

    int f_ok(bool x) {
         if (x) return 42;
         throw 42;
         // (1)
    }
    

    There are two possiblities: 1) It returns 42, 2) it throws, stack is unwound and statements after the throw are not executed. There is no way the function can return without returning a value. (1) is unreachable code, placing a return at (1) can be misleading, and compilers might warn about uncreachable code. The function f_ok is ok.