Why there is no compiler error when return statement is not present?

前端 未结 7 1342
自闭症患者
自闭症患者 2021-01-08 00:19

Unlike Java, in C/C++ following is allowed:

int* foo ()
{
  if(x)
    return p;
// what if control reaches here
}

This oft

7条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-08 00:46

    The obvious answer is: because it's not an error. It's only an error if x is false and if the caller uses the return value, neither of which can necessarily be determined by the compiler, at least in the general case.

    In this particular case (returning a pointer), it wouldn't be too difficult to require a return for all paths; Java does this. In general, however, it's not reasonable in C++ to require this, since in C++, you can return user defined types for which it may be impossible to construct a value (no default constructor, etc.) So we have the situation where the programmer might not be able to provide a return in a branch that he or she knows can't be taken, and the compiler can't determine that the branch can't be taken.

    Most compilers will warn in such cases, when it can determine the flow. All of the ones I've seen also warn in some cases where it's clearly impossible to fall off the end, however. (Both g++ and VC++ warn about:

    int
    bar( char ch )
    {
        switch ( ch & 0xC0 ) {
        case 0x00:
        case 0x40:
            return 0;
    
        case 0x80:
            return -1;
    
        case 0xC0:
            return 1;
        }
    }
    

    , at least with the usual options. Although it's quite clear that this function never falls off the end.)

提交回复
热议问题