Is a return statement mandatory for C++ functions that do not return void?

前端 未结 7 1452
忘了有多久
忘了有多久 2020-11-27 07:31

My Herb Schildt book on C++ says: \"... In C++, if a function is declared as returning a value, it must return a value.\" However, if I write a function wit

7条回答
  •  再見小時候
    2020-11-27 08:11

    It's not mandatory to have a return statement in a function declared as returning non-void and it doesn't have to lead to undefined behaviour.

    Such a function could:

    • Not return, say by entering an infinite loop
    • Return by throwing an exception
    • Call a function that itself does not return, such as std::terminate

    Of course, if a function avoids undefined behaviour by always doing one of the above it probably shouldn't be declared as returning non-void if possible.

    One obvious case where it would need to is if it is a virtual function which for a particular point in a class hierarchy can't return a valid value and always exits via an exception.

提交回复
热议问题