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

后端 未结 9 2339
粉色の甜心
粉色の甜心 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:23

    gcc does not by default check that all code paths return a value because in general this cannot be done. It assumes you know what you are doing. Consider a common example using enumerations:

    Color getColor(Suit suit) {
        switch (suit) {
            case HEARTS: case DIAMONDS: return RED;
            case SPADES: case CLUBS:    return BLACK;
        }
    
        // Error, no return?
    }
    

    You the programmer know that, barring a bug, this method always returns a color. gcc trusts that you know what you are doing so it doesn't force you to put a return at the bottom of the function.

    javac, on the other hand, tries to verify that all code paths return a value and throws an error if it cannot prove that they all do. This error is mandated by the Java language specification. Note that sometimes it is wrong and you have to put in an unnecessary return statement.

    char getChoice() {
        int ch = read();
    
        if (ch == -1 || ch == 'q') {
            System.exit(0);
        }
        else {
            return (char) ch;
        }
    
        // Cannot reach here, but still an error.
    }
    

    It's a philosophical difference. C and C++ are more permissive and trusting languages than Java or C# and so some errors in the newer languages are warnings in C/C++ and some warnings are ignored or off by default.

提交回复
热议问题