Why “not all control paths return a value” is warning and not an error?

后端 未结 7 1783
花落未央
花落未央 2020-12-02 01:48

I was trying to answer this question. As suggested by the accepted answer, the problem with that code is that not all control paths are returning a value. I tried this code

相关标签:
7条回答
  • 2020-12-02 02:24

    Technically it is not guaranteed to be an error if you call a function and that function always throws an exception. For example here is some pseudo code, and you know raiseError always throws.

    MyClass func( params )
    {
         if( allIsValid() )
         {
           return myObject;
         }
         else
         {
            raiseError( errorInfo );
         }
    }
    

    If the compiler cannot see the implementation of raiseError, it will not know that the function is going to throw. So really there is actually no undefined behaviour here. Of course it is good to silence the compiler here, which you can do with either writing a "dummy" return statement after raiseError, or a dummy "throw". I call them "dummy" because they will never be reached in reality. (You can also suppress the warning if you really insist). However there is no error or undefined behaviour.

    0 讨论(0)
提交回复
热议问题