“missing return statement”, but I know it is there

前端 未结 4 921
面向向阳花
面向向阳花 2021-01-06 19:24

Assume I have the following function:

// Precondition:  foo is \'0\' or \'MAGIC_NUMBER_4711\'
// Returns:       -1 if foo is \'0\'
//                 1 if fo         


        
4条回答
  •  不思量自难忘°
    2021-01-06 20:02

    Actually the compiler is doing exactly what it should.

    int transmogrify(int foo) {
        if (foo == 0) {
            return -1;
        } else if (foo == MAGIC_NUMBER_4711) {
            return 1;
        }
        // you know you shouldn't get here, but the compiler has
        // NO WAY of knowing that.  In addition, you are putting
        // great potential for the caller to create a nice bug.
        // Why don't you catch the error using an ELSE clause?
        else {
            error( "transmorgify had invalid value %d", foo ) ;
            return 0 ;
        } 
    }
    

提交回复
热议问题