Why does flowing off the end of a non-void function without returning a value not produce a compiler error?

后端 未结 9 2362
粉色の甜心
粉色の甜心 2020-11-21 07:37

Ever since I realized many years ago, that this doesn\'t produce an error by default (in GCC at least), I\'ve always wondered why?

I understand that you can issue co

9条回答
  •  忘了有多久
    2020-11-21 08:25

    In some limited and rare cases, flowing off the end of a non-void function without returning a value could be useful. Like the following MSVC-specific code:

    double pi()
    {
        __asm fldpi
    }
    

    This function returns pi using x86 assembly. Unlike assembly in GCC, I know of no way to use return to do this without involving overhead in the result.

    As far as I know, mainstream C++ compilers should emit at least warnings for apparently invalid code. If I make the body of pi() empty, GCC/Clang will report a warning, and MSVC will report an error.

    People mentioned exceptions and exit in some answers. Those are not valid reasons. Either throwing an exception, or calling exit, will not make the function execution flow off the end. And the compilers know it: writing a throw statement or calling exit in the empty body of pi() will stop any warnings or errors from a compiler.

提交回复
热议问题