Missing return statement in a non-void method compiles

I encountered a situation where a non-void method is missing a return statement and the code still compiles.
I know that the statements after the while loop are unreachable (dead code) and would never be executed. But why doesn’t the compiler even warn about returning something? Or why would a language allow us to have a non-void method having an infinite loop and not returning anything?

public int doNotReturnAnything() {
    while(true) {
        //do something
    }
    //no return statement
}

If I add a break statement (even a conditional one) in the while loop, the compiler complains of the infamous errors: Method does not return a value in Eclipse and Not all code paths return a value in Visual Studio.

public int doNotReturnAnything() {
    while(true) {
        if(mustReturn) break;
        //do something
    }
    //no return statement
}

This is true of both Java and C#.

13 Answers
13

Leave a Comment