Why is “control reaching the end of a non-void function” just a warning? It is legal?

Is it legal C ++ to define a function with a non-void return type that allows the control to reach the end of the function rather than reach the return statement?

gccand clanggive warnings just for that. Code that makes this legal or are these compilers simply generous?

NCA:

warning: no return statement in function returning non-void [-Wreturn type]

clank:

warning: control reaches the end of the non-void function [-Wreturn-type]

If this is legal, is there a specific behavior for which value will be returned?

+4
2

"Bathsheba", undefined. , , , , , . , :

// My magic function.
// It is forbidden to call it with values between -5 and 5
bool fun (int i) {
    if (i >= 5)
        return true;
    if (i <= -5)
        return false;
}

, . , , , .

Edit: MSalters, -, , . :

// Every member function of SomeClass makes sure 
// that i_ is in the legal range when it done
class SomeClass {
    public:
        SomeClass () : i_{27} {}
    // Possibly more public or private functions that all make sure i_ stays valid
    private:
        bool foo () {if (i_ > 3) return true;}
        int i_;
};

( ) , i_ 4, foo . , , , , "" / .

+4

++ Standard, 6.6.3:

; undefined .

, undefined.

+3

All Articles