"Missing Return Statement" Within If/For/While

Missing return statement within if / for / while

If you put a return statement in the if, while or for statement then it may or may not return a value. If it will not go inside these statements then also that method should return some value (that could be null). To ensure that, compiler will force you to write this return statement which is after if, while or for.

But if you write an if / else block and each one of them is having a return in it then the compiler knows that either the if or else will get executed and the method will return a value. So this time the compiler will not force you.

if(condition)
{
return;
}
else
{
return;
}

Missing return statement for if/else statement

Every return statement is inside an if statement. While it may be logically impossible as written, the compiler needs a return for when none of the if evaluate true.

I recommend:

public int checkGuess(int number, int randomnumber){
int retVal = 0;
this.randomnumber= randomnumber;

if (number == randomnumber) {
retVal = 0;
} else if (number < randomnumber) {
retVal = -1;
} else if (number > randomnumber) {
retVal = 1;
}
return retVal;
}

This solution fixes the compiler problem and improves readability slightly, in my opinion.


Alternatively, there's this solution:

public int checkGuess(int number, int randomnumber){
this.randomnumber= randomnumber;

if (number == randomnumber) {
return 0;
} else if (number < randomnumber) {
return -1;
} else if (number > randomnumber) {
return 1;
} else {
//throw an exception
}
}

Throwing an exception will allow you to get out of the method without returning anything... because arguably, if you get to the final else, something clearly went wrong.

Missing return statement with for loop

The compiler cannot know whether the loop is actually run, therefore you must also have a return statement outside the outer loop.

But then, if I look at your code, I am not sure whether returning is what you really want there. If it is your intention to print the entire matrix, you might want to use a StringBuilder and then use the append method inside the loops. After the outer loop, return a string representation of the builder using the toString method like so:

StringBuilder sb = new StringBuilder();
// loop
sb.append(someValue);
sb.append('\n');
// after loop
return sb.toString();

Missing return statement after if-else

The C++ standard says this, see [stmt.return]/2:

Flowing off the end of a constructor, a destructor, or a function with a cv void return type is equivalent to a return with no operand. Otherwise, flowing off the end of a function other than main results in undefined behavior.

Your operator != does exactly that. It never flows off the end of the function since all control paths end with a return.

Hence the code is correct, and the compiler's diagnostic is wrong.



Related Topics



Leave a reply



Submit