You've got the following:
if (...)
return ...
else if (...)
return ...
else if (...)
return ...
Question: What happens if none of the if
conditions match?
Answer: There'd be a horrible error, since there's no return statement after the final else if
clause. As the above answer says, it doesn't matter that you know there is no way it can fall off the end - the compiler does not know that. To fix the error, you need to do one of the following things:
if (...)
return ...
else if (...)
return ...
else if (...)
return ...
else
return ...
or
if (...)
return ...
else if (...)
return ...
else if (...)
return ...
return ...
Note that the second answer has a return
statement below all the clauses. This is a minor difference, and it doesn't matter as far as your question goes, but if, for example, one of the if
clauses had another conditional inside it, that could the fail to return something. For example:
if (...)
if (...)
return ...
else
...
else if (...)
return ...
else if (...)
return ...
else
return ...
The above would also fail to compile, since there is no return
statement in the nested else
clause.